Example:
export default {
data() {
return {
data1: 1,
data2: 2
}
},
mounted() {
this.data1 = 2
console.log(this.data2)
},
watch: {
data1: {
handler(newData1) {
this.data2 = newData1 * 3
}
}
}
}
Expected behavior: the browser write number 6 to the console
Current behavior: the browser write number 2 to the console
In this example I try to write the modified data2 after changed data1 value, but it write the data2 value before the watcher handler modify it. Is there a way to immediatly run watcher handler after triggering? I know I can use a computed property in this example but I need data in my project.
I tried to set the watcher immediatly property to true but isn't working.
CodePudding user response:
I am not sure what the purpose of your code, but below will work
mounted() {
this.data1 = 2
this.$nextTick(() => {
console.log(this.data2)
})
},
CodePudding user response:
Current behavior: the browser write number 2 to the console
It becauses Vue performs DOM updates asynchronously first run into mounted you made change to data1 (also puts console.log(this.data2)
to callback queue at this point of time this.data2 = 2
thats why you see log 2) it also triggers watch of data1 If you log data2 here you see value of 6.
In order to wait until Vue.js has finished updating the DOM after a data change, you can use Vue.nextTick(callback) immediately after the data is changed
mounted() {
this.data1 = 2
this.$nextTick(() => {
console.log(this.data2); // 6
})
}
or use Vue.$watch
- Watch an expression or a 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
})
}