1. Overview of Vue watch
Vue's watch listener formats come in two flavors: 方法格式
and 对象格式
listener .
- The listener in the method format can only
监听简单数据类型
, for example:Number、String
, ... cannot monitor changes in object properties, nor can it be automatically triggered when entering the page; - Object format listeners can listen
对象属性
for changes. Under certain conditions, data changes can also be monitored when the page is loaded;
2. Listener method of Vue object
- The key name is split to monitor
某一个属性
the change of the object;
the property name.
is separated from the object by and引号
wrapped to monitor a certain property of the object
data() {
return {
obj:{
name:'andy',
age:18
}}},
watch:{
'obj.name'(newval.oldval) {
// 代码实现
}
}
- computed + watch, monitor
某一个
the property change of the object;
computed:{
ageVal() {
return this.obj.age;
}
}
watch:{
ageVal(newval,oldval) {
// 代码实现
}
}
- deep In-depth monitoring, monitoring
所有属性
changes in objects;deep:true
When deep monitoring is enabled, any property value change will trigger deep monitoring;- deep In-depth monitoring can only get the latest value;
- Deep monitoring is not recommended, it is easy to cause page freezes, because deep deep monitoring needs to traverse all nested properties in the monitored object;
obj:{
handler(val) {
// 代码实现 val 值是 obj 整个对象
},
deep:true // deep 为 true 时,开启深度监听
// immediate:false 当immediate 值为 true 时,刚载入页面时,也可监听数据的变化
}