After triggering, VueJS will immediately run the watcher handler

Illustration:

export default {
    data() {
        return {
            value1: 1,
            value2: 2
        }
    },
    mounted() {
        this.value1 = 2
        console.log(this.value2)
    },
    watch: {
        value1: {
            handler(newValue1) {
                this.value2 = newValue1 * 3
            }
        }
    }
}

Anticipated outcome: the browser displays number 6 in the console

Current result: the browser displays number 2 in the console

In this scenario, I attempted to update the value of 'value2' after changing the value of 'value1', but it shows the original 'value2' instead of the modified one. Is there a method to immediately execute the watcher handler after triggering? I understand that for this example, computed properties can be utilized, however, I have specific data requirements in my project.

I made an effort to set the immediate property of the watcher to true, however, it did not work as expected.

Answer №1

To optimize your code, consider using a computed property for data2

export default {
            data() {
                return {
                    data1: 1
                }
            },
            mounted() {
                this.data1 = 2
                console.log(this.data2)
            },
            computed: {
              data2() {
                return this.data1 * 3 
              }
            }
         }

Answer №2

The observer will not activate during the execution of your mounted() function; you must wait until the function has completed. This behavior is typical in JavaScript and is not specific to Vue.

Answer №3

When the browser runs, it outputs the number 2 to the console.

This occurs because Vue updates the DOM asynchronously during the first mount. When you make a change to data1 (and add console.log(this.data2) to the callback queue) at this point, this.data2 = 2 is set, resulting in the log of 2. It also triggers the watch on data1. If you log data2 here, you will see the value as 6.

To wait for Vue.js to finish updating the DOM after a data change, you can use Vue.nextTick(callback) right after changing the data.

mounted() {
  this.data1 = 2
  this.$nextTick(() => {
     console.log(this.data2); // 6
  })
}

Alternatively, you can use Vue.$watch to watch an expression or computed function on the Vue instance for changes:

data() {
  return {
    data1: 1,
    data2: 2
  }
},
watch: {
  data1: function(val) {
    this.data2 = val * 3
  }
},
mounted() {
  this.data1 = 2
  this.$watch('data2', (newVal) => {
    console.log(newVal) // 6
  })
}

Answer №4

Although I'm uncertain about the intention behind your code, the following modification should suffice:

  mounted() {
    this.value = 2
    this.$nextTick(() => {
      console.log(this.result)
    })
  },

Answer №5

In accordance with another solution, the default behavior is as expected and can usually be resolved by utilizing the nextTick method. However, in cases where a computed property is used instead, as proposed in yet another response, this may not always be necessary.

For Vue 3 users, there is an option to modify this behavior using the flush parameter:

mounted() {
    this.data1 = 2
    console.log(this.data2) // 6
},
watch: {
    data1: {
        handler(newData1) {
            this.data2 = newData1 * 3
        },
        flush: 'sync'
    }
}

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

Encountering the error message "Unable to locate module '.nextserverpages-manifest.json'" while attempting to include `babel.config.js` in a Next.js application

During the process of setting up testing for my current next app, we incorporated some new dependencies including jest, babel-jest, @babel/preset-env, @babel/preset-react, and react-test-renderer. We also created a babel.config.js file to configure Babel s ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

What is the best way to locate a specific item within an array of objects, especially when each object has the potential to contain an array of objects of the

I am grappling with the challenge of finding a specific object within an array of objects, where the desired object may be nested within another array of one of the objects. I have experimented with various iterations of forEach loops and recursion method ...

The dynamic duo of MongoDB and Prisma: forging a groundbreaking one-to-many relationship

Is it possible to establish a one-way m-to-n relationship without requiring both collections to have each other's ids? I am attempting the following: model Country { id String @id @default(auto()) @map("_id") @db.ObjectId ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

Introduce new router events, routeChangeStart and routeChangeComplete, within the client-side components of next js 14

I am currently working on a Next.js v14.0.4 project and I am facing an issue with implementing a top loader progress bar using the NProgress package for route changes triggered by Link or router.push(). The handleRouteChangeStart and handleRouteChangeCom ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Clearing AsyncStorage in React Native

It has come to my attention that I am spending a significant amount of time debugging redux actions in react-native that are being persisted to AsyncStorage using redux-persist. There are instances where I wish I could simply clear AsyncStorage in order to ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

What is the proper way to retrieve items from an Array that have an index that is evenly divisible by

let numbers = [4, 5, 7, 8, 14, 45, 76]; function getEvenElements(arr) { let evenArray = []; for (let i = 0; i < arr.length / 2; i++) { evenArray.push(arr[2 * i]); } return evenArray.filter(num => num !== undefined); } alert(getEvenEle ...

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...

The authentication middleware is being executed for all routes within my app.js file, despite my intention to only apply it to a single route

I have developed a requireAuth middleware and integrated it into my app.js. In app.js, I have also imported all the routes from the routes folder. Each route.js file contains multiple chained routes. When I include the auth middleware in one of those files ...

The Terser Plugin encounters compatibility issues when used with Vue CLI version 5 during the Vue build process

I am encountering an issue while attempting to generate a production build using the configureWebpack settings. Terser does not seem to be running during the build process. The code is not being minimized or uglified as expected, even after trying hidden- ...

How to run a PHP script using JavaScript?

I am planning to execute a quick php script once users exit my website. Moreover, I am looking to transfer a variable from my javascript to php, but I am unsure how to integrate the php file and pass it a variable. Unfortunately, the php script is not runn ...

Convert JSON data into a compressed single row format

I have a JSON file generated from PhantomJS, and it appears as follows: { "startedDateTime": "2015-04-27T12:48:47.107Z", "time": 281, "request": { "method": "GET", "url": "http://www.example.com/DE/de/shop/welcome.html;jsessio ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Navigating through different components in React is made possible with React Router

I have views in my application that depend on each other. For example, in one view a user can choose an item from a list (generated on the server), and in the next view they can perform operations on that selected item. The item is passed to the second v ...

Exporting modules from Node.js using Express framework is a common

Encountering an issue with this error message Error: app.get is not a function This section shows my configuration in config/express.js var express = require('express'); module.exports = function(){ var app = express(); app.set(&apo ...

Is there a way to reverse the JSON.stringify method?

I need help with decoding a string that contains arrays and JS objects which were originally converted using JSON.stringify function. Can someone guide me on how to accomplish this? Thank you for your assistance. ...