What causes Vue to only update once when there are two closely timed mutations to reactive data?

Can you take a look at this simple example?

export default {
  data() {
    return {
      name: "Amy",
      age: 18,
    };
  },
  computed: {
    combinedDataForWatching() {
      return {
        name: this.name,
        age: this.age,
      };
    },
  },
  watch: {
    combinedDataForWatching() {
      console.log("Triggered!");
    },
  },
  mounted() {
    setTimeout(() => {
      this.name = "Bob";
      this.age = 20;
    }, 1000);
  },
};

The message "Triggered!" will only be logged once, can you explain why?

What is the mechanism behind Vue's batch update detection?

Answer №1

According to the Vue reactivity guide:

Vue updates the DOM asynchronously, buffering all data changes within the same event loop. When a data change is detected, it adds it to a queue and ensures that duplicate changes are not processed multiple times. This de-duplication process helps prevent unnecessary calculations and manipulations of the DOM. Subsequently, during the next event loop "tick", Vue flushes the queue and executes the already streamlined work.

Thus, both watch triggers happen within the same update cycle and get consolidated into a single call by the reactivity system.

Answer №2

After consulting with @Dan, we have determined that we should wait for the next tick. In the Vue.js Composition API, this issue can be resolved by utilizing the nextTick function provided by vue. For a practical demonstration, you can refer to this example on the Vue.js SFC REPL, which illustrates how nextTick is used to trigger a watcher twice.

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

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

A chart using JavaScript that displays text values instead of a traditional website

I am a student with no background in programming, however, for my project I need to create a chart based on values from a txt file to display sensor data. I came across a chart that retrieves its values from a website, but I would like to modify it so it c ...

What is the process for dynamically incorporating JavaScript files during compilation to serve as input for browserify?

Within our project's structure, there exists a directory housing multiple js files. The possibility of adding or removing these files later on is present. Currently, we have a file named main.js where each file is imported and a map is created (using ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Script CSP was declined from loading

After implementing CSP on my Nuxt website successfully, I encountered an issue when I added addMeta:true to the CSP object. This resulted in the following error message: https://i.sstatic.net/H5eTn.png Error message received: Refused to load the script ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Implementing NodeJS to showcase an array of items - the step-by-step guide

I'm currently setting up a webpage to display a list of books using NodeJS, but despite my efforts, the page remains blank when I launch it. My goal is to showcase the array of books on the page, and so far, here's the code that I have written. A ...

Session availability extends to subdomains, even though it may not be visible in a physical

Currently in the process of building a website Red Sec using a single account for all subdomains: Latest Updates Community Forum Personal Blog News Feed Support Us All pages share the same layout with different content by linking them to . Below i ...

Modify the class of an input while typing using Jquery

Recently, I created a form using Bootstrap 4. The validation process is done through a PHP file with an AJAX call and it's functioning correctly, except for one issue. I want the input class to switch from "invalid" to "valid" as soon as the user begi ...

The alert() function in PHP does not function as expected and instead prints to the console

My attempt to display an alert is not working and I'm not sure what I might be missing. Can someone please help me pinpoint the issue? //my.php if(mail($to, $subject, $message, $headers)) { $message = "Mail sent."; echo "<script type=&apo ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

In a scenario where multiple fields need to be incremented, one can accomplish this by incrementing one field every time while also increasing the other field only if it exceeds a

When trying to decrement class_number, everything works fine. However, the issue lies with number_of_classes not being decremented due to the usage of the $gt operator. posts.update({ 'title':doc.title, 'author':doc.author, 'class ...

Is there a way to remove specific items from my array in Vue.js?

Essentially, I am using an HTML select element that is populated with arrays of registered users. <label > <b> <i style="opacity:0.8">Users:</i> </b> </label>&nbsp;&nbsp; <select class=&quo ...

What is the best way to dynamically update a state that is deeply nested?

Is there a way to update the object using key: 1311 and retrieve the updated state while not knowing its exact location but only its key value? state = { iow: [ { key: 1, iow_description: "EARTH WORK", unit: null, rate: nul ...

What is the mechanism behind the operation of asynchronous functions within the bcrypt() method in Node.js?

const bcrypt = require('bcrypt'); const saltRounds = 8; const plainPassword1 = "12345"; const plainPassword2 = "56789"; const func1 = async (password, plainP) => { console.log("hashing password"); const h ...

Utilize store functions (such as dispatch and getState) in external modules like webSockets, rather than within components

I have implemented React and Redux, along with webSocket to handle server side events. Currently, I can dispatch actions from a component by assigning a function to the dispatcher using the mapDispatchToProps() function. But what if I want to trigger an ...

How can I remove the div container every time the submit button is clicked?

I am currently working on a form that is capturing values as shown below. <form role="form" id="calculate"> <div class="form-group"> <select class="form-control" id="paper"> < ...

Is it possible to conceal the row selection column in the DataTable component of PrimeVue?

I am seeking a solution to selectively conceal the row selection column within the DataTable component. For instance, I aim to display it only when a specific prop is provided: <DataTable> <Column v-if="propName == true" :selectionMode ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...