data() {
return {
demo: {
name: ' '
},
value: ' '
};
},
computed: {
newName() {
returnthis.demo.name; } }, watch: { newName(val) { this.value = val; }}Copy the code
If watch monitors an object, it cannot be used directly. In this case, we can use computed attributes to do so.
watch: {
obj: {
handler(newName, oldName) {
console.log('obj.a changed');
},
immediate: true,
deep: true}}Copy the code
Deep means to look deep, and the listener will go down one layer at a time, adding the listener to all the properties of the object, but the performance overhead is very high
watch: {
'obj.a': {
handler(newName, oldName) {
console.log('obj.a changed');
},
immediate: true,
// deep: true}}Copy the code
Handler method and immediate attribute
One of the features of Watch is that it will not perform the initial binding until the monitored data changes.
watch: {
firstName: {
handler(newName, oldName) {
this.fullName = newName + ' '+ this.lastName; }, // execute the handler method immediately after declaring firstName in wacth:true
}
Copy the code
The cancellation of watch
Components are often destroyed. Usually, watch is written in the option of the component, and it will be destroyed along with the destruction of the component.
However, if we write watch as follows, then we have to log out manually
const unWatch = app.$watch('text', (newVal, oldVal) => {
console.log(`${newVal} : ${oldVal}`); }) unWatch(); // Log out of watch manuallyCopy the code
App. $watch returns the unWatch method (manually destroyed).