1# watch 监听器的三种监听方式
| 类型 | 特点 |
|---|
| 普通监听 | 只有在值发生改变时才执行监听函数,不会在第一次绑定值时执行。 |
| 立即监听 | 设置immediate: true,可以在第一次绑定值时执行监听函数,包括初始绑定时的操作。 |
| 深度监听 | 设置 deep: true ,可监听对象内属性的变化,即使是对象内属性的变化也能触发监听器,适用于深度监听对象属性变化。 |
watch: {
value1: function(newValue, oldValue) {
console.log('数值发生改变:', newValue);
},
value2: {
handler(newValue, oldValue) {
console.log('数值发生改变:', newValue);
},
immediate: true
},
obj: {
handler(newObj, oldObj) {
console.log('对象属性发生改变:', newObj);
},
deep: true
}
}
2# watch 监听变量
<template>
<div>
<p>变量: {{ myVar }}</p>
<p>数组: {{ myArray }}</p>
<p>对象: {{ myObject }}</p>
<button @click="changeData">改变数据</button>
</div>
</template>
<script>
export default {
data() {
return {
myVar: 'Hello',
myArray: [1, 2, 3],
myObject: {
key1: 'oldValue-1',
key2: 'oldValue-2'
}
};
},
methods: {
changeData() {
this.myVar = 'Vue';
this.myArray.push(4);
this.myObject.key1 = 'newValue-1';
this.myObject.key2 = 'newValue-2';
}
},
watch: {
myVar: function(newVal, oldVal) {
console.log('myVar 发生变化:', newVal);
},
myArray: {
handler: function(newArray, oldArray) {
console.log('myArray 发生变化:', newArray);
},
deep: true
},
myObject: {
handler: function(newObj, oldObj) {
console.log('myObject 发生变化:', newObj);
},
deep: true
},
"myObject.key2": {
handler: function(newObj, oldObj) {
console.log('myObject.key2 发生变化:', newObj);
},
}
}
};
</script>