watch: { firstName: { handler(newName, oldName) { this.fullName = newName + ' ' + this.lastName; }, // The first Name method was declared by the representative in wacth, and the handler method was executed immediately after the first Name method was declared. immediate: true } } //Did the copy code notice the handler? We bound a handler method to firstName. The watch method we wrote before actually defaults to this handler. Vue.js will handle this logic, and finally compiles it into this handler. //And immediate:true means that if first Name is declared in wacth, the handler method in it will be executed immediately. If false is the same as our previous effect, it will not be executed at the time of binding. watch:{ // Watch is fine with this grammar. There's... in the document. Depending on the requirements, you can also watch data directly and use deep:true for in-depth observation 'data.status':{ handler:(val,oldVal)=>{ //Tasks to be performed //I don't know how to modify the data in this.data. Please let me know if you know. //What you know now is that you update the data by directly modifying Store.state, and of course the effect is the same as that of modifying this.data. }, // Deep observation deep:true } }, // Or: watch: { msg: { handler(newValue, oldValue) { console.log(newValue) }, deep: true } } // Or computed attributes computed: { channel() { return this.msg.channel } }, watch:{ channel(newValue, oldValue) { console.log('new: %s, old: %s', newval, oldVal) //Here you can perform what you want to do once the monitored value changes } }
Write off watch
Why cancel watch? Because our components are often destroyed, such as we jump a route, jump from one page to another, then the original page watch is useless, at this time we should cancel the original page watch, otherwise it may lead to built-in overflow. Fortunately, watches are usually written in component options, and they will be destroyed as the component is destroyed.
const app = new Vue({ template: '<div id="root">{{text}}</div>', data: { text: 0 }, watch: { text(newVal, oldVal){ console.log(`${newVal} : ${oldVal}`); } } });
But if we write watch in the following way, we have to cancel it manually, which is actually very simple.
const unWatch = app.$watch('text', (newVal, oldVal) => { console.log(`${newVal} : ${oldVal}`); }) unWatch(); // Manual cancellation of watch
app.$watch calls return a value, the unWatch method. If you want to cancel the watch, just call the unWatch method.