Is it possible to link a Vue.js data property to a local variable while also incorporating its setter function?

Here is a simple example to showcase:

<template>
  <div>
    {{ count }}
    <button @click="click">Click</button>
  </div>
</template>

<script>

export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    click() {
      this.count++
    }
  }
};
</script>

We have a data property called count and a button that increments the count when clicked.

Now, let's explore an alternative approach for some reason:

click() {
  let count = this.count
  count += 1
}

The idea here is to first assign the data property to a local variable, then increase the local variable count in order to trigger Vue's reactivity.

Given that Vue uses Object.defineProperty's setter for data properties, is it feasible to mimic those setters?

Could this method work as intended?

Update

I am aiming to simplify the following code snippet:

<script lang="ts">
export default {
  data() {
    return {
      isALoading: false,
      isBLoading: false
    };
  },
  methods: {
    hitAPI(type: "A" | "B") {
      if (type === "A") {
        this.isALoading = true;
        fetch(someAPI)
          .then(() => {
            this.isALoading = false;
          })
          .catch(() => {
            this.isALoading = false;
          });
      } else {
        this.isBLoading = true;
        fetch(someAPI)
          .then(() => {
            this.isBLoading = false;
          })
          .catch(() => {
            this.isBLoading = false;
          });
      }
    }
  }
};
</script>

Answer №1

Transferring a setter in the form of a local variable is not a feasible task.

One way to handle this situation is by encapsulating the property within a method or another object that has its own setter:

click() {
  const self = this
  const wrapper = {
    get count() { return self.count },
    set count(x) { self.count = x }
  }

  wrapper.count++
}

It appears that you might be experiencing an XY problem; what specific goal are you aiming for with this approach?

The most straightforward solution may just involve reassigning the local variable back to the data property to trigger the update:

click() {
  let count = this.count

  // Update the local variable
  count++

  // Reassign to trigger the update
  this.count = count
}

UPDATE

A dynamic approach involves accessing the property based on its string name:

hitAPI(type: "A" | "B") {
  const prop = type === "A" ? "isALoading" : "isBLoading"
  this[prop] = true

  fetch(someAPI).finally(() => {
    this[prop] = false
  })
}

Alternatively, using async/await:

async hitAPI(type: "A" | "B") {
  const prop = type === "A" ? "isALoading" : "isBLoading"
  this[prop] = true

  try {
    await fetch(someAPI)
  } finally {
    this[prop] = false
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...

Creating dynamic animations in three.js involves using time as a crucial

As someone who is new to Javascript, I am struggling to understand how the time argument functions within the animate function provided below. It seems that the animate function requires a time argument, but when called as a callback in setAnimationLoop, ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

Click once to change the element, but it will remain changed and will not revert back no matter how many times you

After the first click displaying "X" and then changing to "O" in my tic-tac-toe JavaScript game, subsequent clicks only show "O", failing to switch back to "X". I am currently working on creating a tic-tac-toe game using JavaScript. Upon the first click, ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Updating the select input value in Vuetify using the prepend-item event

Is there a way to update the select value in a Vuetify select by clicking on a specific item that is prepended? I'm having an issue where the model doesn't update the item-text in the select input. <v-select :items="loadedTasks" v- ...

Having trouble with connect-busboy not calling the callback when using NodeJS, AngularJS, and File Upload?

Click here for the sources I am currently working on implementing a NodeJS server that allows file uploads using connect-busboy from AngularJS with the help of angular-file-upload for later analysis. The issue I'm encountering is that the callback f ...

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

Converting JavaScript TimeStamp to MilliSeconds

How can I convert a timestamp like 09-MAR-11 04.52.43.246000000 AM to milliseconds using JavaScript? I need to achieve this conversion within JavaScript only. Any help would be greatly appreciated. Thank you. ...

Is there a way to access every item that includes a particular attribute and attribute term within the woocommerce-rest-api?

Struggling to retrieve products that have the "x-attribute" and "x-attribute-term" using Node.js with the WooCommerce REST API library from here. I've explored solutions on stackoverflow and other sites but none seem to work. Atte ...

Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple). The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday ...

Unable to trigger ng-click event in IE browser, while it functions properly in Chrome

<select id="from" multiple="multiple" name="list" ng-model="selectedVal"> <optgroup label= "{{geo.Geo}}" ng-repeat="geo in Geographies"> <option id="{{country.CountryKey}}" ng-repeat="country in geo.Country" ng-click="arrayPush( ...

Create a bookmarklet that triggers a function to download files

I am interested in developing a bookmarklet that is capable of downloading a remote javascript file containing a defined function, and then executing that function with predetermined parameters. Below is a typical "download-and-run-remote-script" bookmark ...

Issue with Accordion Panel Content Scroll Bar

Hello there, I've encountered a puzzling problem with my website. My objective is to insert a Time.ly Calendar widget into one panel of my accordion. On this page, "TOURNAMENTS: , the widget appears exactly as desired. However, when I replicate the c ...

Experiencing incorrect cursor location in JavaScript

I am facing an issue where I need to insert a token after selecting from a context menu at the caret position inside a contenteditable div. This works fine when the caret position is within a single line. However, in my case, the range offset value become ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

The Button.Click event is failing to trigger

Just starting out with JQ and I've put together this fiddle: http://jsfiddle.net/SZ6mY/7/ Basically, I'm looking to display an "ALERT" message when the "C" button is clicked. Also, I'm curious about how to capture the value 7 in a variable ...

Why is My JQuery Button Data Null?

I am facing an issue with a button where I want to pass the HTML object as a parameter to a JavaScript function. The objective is to print the data-hi attribute value from the element in the button. HTML BUTTON <button type = "button" onclick = "whoIs ...

Retrieving XML using JavaScript with AJAX

Having trouble retrieving XML data using JavaScript and Ajax. The script takes too long (up to 45 seconds) to collect the data from the database and return it as XML. Everything works fine when loading the data locally, so no issues with cross-domain. An ...