侦听器
当使用watch侦听data中的数据的变化,watch中的属性一定是data中已经存在的数据。
当需要监听一个对象的改变时,普通的watch方法无法监听到对象内部属性的变化,只有data中的数据才能监听到变化,此时就需要deep属性对对象进行深度监听
watch它没有缓存,它一般用于业务逻辑使用,不在模板中使用,做的是数据的监听处理
支持异步处理
实现一个基本的watch监听
【html】
<div id="app">
title<input type="text" v-model="title">
</div>
【js】
const app = new Vue({
el: '#app',
data: {
title: 'hello'
},
watch: {
// 写函数的方式,它默认在初始化时是不会被执行,只有你监听的属性数据发生的改变,它才执行
// title(newValue, oldValue) {
// console.log(newValue, oldValue,this);
// // this 指向vue实例化对象
// if (newValue.length >= 3) {
// console.log('长度过长');
// }
// console.log(newValue);
// }
// 在初始化时,我就想让他执行1次
title: {
handler(newValue, oldValue) {
console.log(newValue)
},
// 让侦听器,初始时就执行1次
immediate: true
}
}
})
==》
分步骤实现
watch: {
// 分步骤实现
title: [
n => console.log(0, n),
{
handler(newValue, oldValue) {
console.log(1, newValue)
},
immediate: true
},
n => console.log(2, n)
]
}}
==》实现对引用类型的监听
【html】
<div id="app">
title<input type="text" v-model="title">
<hr>
info.title<input type="text" v-model="info.title">
<hr>
<button @click="addItem">++++</button>
</div>
【js】
const app = new Vue({
el: '#app',
data: {
title: 'hello',
info: { title: '' },
// arr: [1, 2, 3],
arr: [{ id: 1 }, { id: 2 }, { id: 3 }]
},
watch: {
// 引用类型 'info.title' => split('.') => for => 取对象中的数值
// 在引用类型时,新值和旧值是一样的结果
// 推荐 ,监听具体到对象中的某一个属性值
'info.title'(n, o) {
console.log(n);
},
// 数组中,监听指定的索引值的变化
// 'arr.1'(n){
// console.log(n);
// },
'arr.1.id'(n) {
console.log(n);
},
methods: {
addItem() {
// this.arr.push(Date.now()) //不会触发
// this.arr[1] ++
// this.arr[1].id ++
// 引用地址更换了
// this.arr = [{ id: 1 }, { id: Date.now() }, { id: 3 }]
}
}
})
==>
深度监听
【js修改watch部分】
// 深度监听,对应的就是引用类的监听,一般不要常用,影响性能
info: {
handler(n, o) {
console.log(n, '深度');
},
// 深度监听
deep: true
},
arr: {
handler(n, o) {
console.log(n, '深度');
},
// 深度监听
deep: true
}
==》通过api实现监听
【html】
<div id="app">
title<input type="text" v-model="title">
<hr>
<button @click="addItem">++++</button>
</div>
【js】
const app = new Vue({
el: '#app',
data: {
title: 'hello'
},
mounted() {
// 通过Api方法实现监听,它可以手动来停止
this.stop = this.$watch('title', n => console.log(n))
},
methods: {
addItem() {
// 停止监听
this.stop()
}
}
})