什么是侦听属性(watch)
- 功能:使用watch来监视和响应Vue实例上的数据变动
- 作用:使用watch监视某个数据变化时做些事情,例如发送网络请求或更新DOM元素
- 业务场景:表单验证、数据筛选、实时聊天、购物车操作、数据可视化等
如何使用侦听属性(watch)
- 侦听数据的变量名字需要与监听器中的方法名一致
- 可以通过参数获取侦听数据的最新值和上一次的值
watch基础用法
侦听input输入框的数据变化(当数据改变时,控制台打印最新的数据和旧数据)
<div id="app">
<input type="text" placeholder="name" v-model="name"><br />
<span>{{message}}</span>
</div>
<script type="text/javascript">
let vm = new Vue({
el: '#app',
data: {
name: '张三',
message: ''
},
//监视
watch: {
name: function (newValue, oldValue) {
let msg = `name值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
this.message = msg
}
}
})
</script>
watch配置项属性
- handler:指定 "watch" 函数的回调函数。
- deep:深度监听,递归监听对象或数组中的所有属性,不论其被嵌套多深, 默认false
- immediate:在组件实例化时立即执行 "watch" 函数, 默认false
<div id="app">
<input type="text" placeholder="name" v-model="name"><br />
<hr>
<span>{{clickCount}}</span>
<button @click="clickCount++">clickCount++</button>
<hr>
<span>{{demo.name}}</span>
<button @click="demo.name=clickCount">修改demo.name</button>
<hr>
<span>{{school}}</span>
<button @click="school={ id: 2}">修改school</button>
<button @click="school.score=88">school.score</button>
</div>
<script type="text/javascript">
let vm = new Vue({
el: '#app',
data: {
name: '张三',
clickCount: 0,
school: {
id: 1,
score: '99',
remark: 'A',
},
demo: {
id: 2,
name: '测试'
}
},
//监视
watch: {
clickCount: function (newValue, oldValue) {
let msg = `clickCount值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
},
name: {
immediate: true,//vue 实例化时立即执行, 默认false
handler(newValue, oldValue) {
let msg = `name值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
}
},
// 监视多级结构中某个属性的变化
"demo.name": {
handler(newValue, oldValue) {
let msg = `demo.name值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
}
},
// 监视多级结构中所有属性的变化
"school": {
deep: true,//深度监听,不论其被嵌套多深, 默认false
handler(newValue, oldValue) {
let msg = `school值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
}
}
}
})
</script>
$watch使用方法
<script type="text/javascript">
let vm = new Vue({
el: '#app',
data: {
name: '张三',
school: {
id: 1,
score: '99',
remark: 'A',
},
},
})
//正常写法1
vm.$watch('school.id', function (newValue, oldValue) {
let msg = `$watch--school.id值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
}, {
immediate: true
})
//正常写法2
vm.$watch('school.remark', {
immediate: true,//vue 实例化时立即执行, 默认false
handler(newValue, oldValue) {
let msg = `$watch--school.remark值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
}
})
//简写,这里this 是windos
vm.$watch('school.score', (newValue, oldValue) => {
console.log(this);
let msg = `$watch--school.score值改变了:[${oldValue}]变成了[${newValue}]`;
console.log(msg);
})
</script>