#watch
类型:{ [key: string]: string | Function | Object | Array}
详细:
一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。组件实例将会在实例化时调用 $watch(),参阅 $watch,了解更多关于 deep、immediate 和 flush 选项的信息。
示例:
const app = Vue.createApp({
data() {
return {
a: 1,
b: 2,
c: {
d: 4
},
e: 'test',
f: 5
}
},
watch: {
a(val, oldVal) {
console.log(`new: ${val}, old: ${oldVal}`)
},
// 字符串方法名
b: 'someMethod',
// 该回调会在任何被侦听的对象的 property 改变时被调用,不论其被嵌套多深
c: {
handler(val, oldVal) {
console.log('c changed')
},
deep: true
},
// 该回调将会在侦听开始之后被立即调用
e: {
handler(val, oldVal) {
console.log('e changed')
},
immediate: true
},
// 你可以传入回调数组,它们会被逐一调用
f: [
'handle1',
function handle2(val, oldVal) {
console.log('handle2 triggered')
},
{
handler: function handle3(val, oldVal) {
console.log('handle3 triggered')
}
/* ... */
}
]
},
methods: {
someMethod() {
console.log('b changed')
},
handle1() {
console.log('handle 1 triggered')
}
}
})
const vm = app.mount('#app')
vm.a = 3 // => new: 3, old: 1
注意
注意,不应该使用箭头函数来定义 watcher 函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue))。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向组件实例,this.updateAutocomplete 将是 undefined。
参考 Watchers |