1.watch的功能
从vue.js的Api文档中可以得知:watch是一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch()
,遍历 watch 对象的每一个 property。
代码示例
<template>
<div class="attr">
<h1>watch属性</h1>
<h2>{{ $data }}</h2>
<button @click="() => (a += 1)">修改a的值</button>
</div>
</template>
<script>
export default {
data() {
return {
a: 1,
b: { c: 2, d: 3 },
f: {
g: 4
}
},
};
watch: {
a: function(val, oldVal) {
this.b.c += 1;
},
"b.c": function(val, oldVal) {
this.b.d += 1;
},
"b.d": function(val, oldVal) {
this.f.g += 1;
},
deep: true
}
}
};
</script>
注意,不应该使用箭头函数来定义 watcher 函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue)
)。理由是箭头函数绑定了父级作用域的上下文,所以 this
将不会按照期望指向 Vue 实例,this.updateAutocomplete
将是 undefined。