watch(监听器 监听属性)
当需要在数据变化时执行异步或开销较大的操作时,使用监听器是最有用的
虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的侦听器。这就是为什么 Vue 通过 watch 选项提供了一个更通用的方法,来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的 。
### html代码
<div id="app">
{{msg}}
<br>
a:<input type="text" v-model.number="a">
<br>
+
<br>
b:<input type="text" v-model.number="b">
<br>
=
<br>
<output>{{total}}</output>
</div>
### js代码
new Vue({
el: '#app',
data: {
msg: 'hello',
a: 0,
b: 0,
total: 0
},
methods: {},
// 监听 侦听
watch: {
a(newValue, oldValue) {
this.total = this.a + this.b;
},
b(newValue, oldValue) {
this.total = this.b + this.a;
}
}
})
### 深度监听
### js代码
new Vue({
el: '#app',
data: {
msg: 'hello',
a: 1,
obj: {
name: 'zhangsan',
age: 12
},
},
watch: {
a(newValue, oldValue) {
console.log('a数据发生变化...');
},
/* obj(newValue, oldValue) {
console.log('obj数据发生变化...');
} */
// 深度监听 //递归监听
obj: {
handler(newValue, oldValue) {
console.log('obj数据发生变化...');
},
// 深度监听
deep: true
}
},
methods: {
changeObj() {
// 更改内部数据
this.obj.name = 'lisi';
}
}
})
### html代码
<div id="app">
{{msg}}
<br>
{{obj}}
<button @click="changeObj">更改obj</button>
</div>