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

Issue with electron-vue: Unable to modify Vuex state when using RxJS subscribe

I need help with my code involving two functions in the mutations and two pieces of state const state = { files: [], uploadProgress: 0 } const mutations = { SET_UPLOAD_IMAGE: (state, files) => { state.files = files }, UPLOAD_IMAGE: ( ...

Securely Upload Files with JavaScript

Are there any methods to utilize javascript or ajax for encrypting file uploads securely? If so, could you provide a sample code snippet or direct me to a functional example? ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Attempting to save data to a .txt file using PHP and making an AJAX POST request

I have been facing an issue while trying to save a dynamically created string based on user interaction in my web app. It's just a simple string without anything special. I am using ajax to send this string to the server, and although it reaches the f ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

Setting timeouts during Vue-cli unit testing can help improve the efficiency and accuracy of your tests

I have been running vue unit tests using the following command: vue-cli-service test:unit However, I am encountering an issue where some unit tests require a response from the server, causing them to take longer to execute. Is there a way for me to man ...

Conceal object after a brief pause

Why does the element hide immediately instead of slowly fading out? I can't figure out why it doesn't first display the "P" tag and then gradually hide it. Please help me solve this issue. var step = 0.1; var delay = 90000; var displayMe = fun ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

Sending Java Servlet JSON Array to HTML

I am currently engaged in a project that requires extracting data from a MySQL database and implementing pagination. My approach involves utilizing JSON AJAX and JavaScript, although I am fairly new to JSON and AJAX. After successfully retrieving the neces ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...

Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, ...

Despite containing elements, Array.length incorrectly reports as 0 in React, JavaScript, and TypeScript

I have been working on storing persistent data for my Electron app using electron-json-storage. Initially, I tried using neDB but encountered an error, so I switched to another method. However, it seems that the issue is not with neDB but rather with my ow ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

How do I ensure my object is fully constructed before sending it in the response using NodeJS Express?

Currently, I am in the process of constructing a result_arr made up of location objects to be sent as a response. However, my dilemma lies in figuring out how to send the response only after the entire array has been fully constructed. As it stands, the re ...

Why is the Zip archive downloader not functioning properly when using Node.js and Archiver (Unexpected end of archive error)?

Looking to download multiple files using archiver with express. The server should respond to a post request from the client by sending a .zip file. However, there seems to be an issue where WinRAR displays an error message "! 98I9ZOCR.zip:Unexpected end of ...

Endless Loop Issue with Google Maps API Integration in NextJS-React

Currently struggling to troubleshoot an infinite loop issue in my React function component map. I've spent a considerable amount of time analyzing the code and suspect that it might be related to the useEffects, but I'm unable to resolve it. Atta ...

I'm curious about how I can apply @media queries given that certain phones possess higher resolution than computers

There seems to be a common recommendation to utilize @media queries for adjusting CSS based on whether the user is on mobile or not. However, I'm a bit confused because my phone has a width of 1440p while my computer has 1920p. Should I consider apply ...

Utilizing the keyword 'this' within a function of a JavaScript class that is invoked with the .map method

I am working with the RegisterUser class which contains various methods and properties: class RegisterUser { constructor(username, password, ispublic){ this.username = username; this.password = password; this.ispublic = ispublic; this.id ...