Vue-watch listens to object properties

1. Overview of Vue watch

Vue's watch listener formats come in two flavors: 方法格式and 对象格式listener .

  1. 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;
  2. 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

  1. 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) {
    
     
		// 代码实现
	}
}
  1. computed + watch, monitor 某一个the property change of the object;
computed:{
    
    
     ageVal() {
    
    
           return this.obj.age;
     }
}
 watch:{
    
    
     ageVal(newval,oldval) {
    
    
           // 代码实现
     }
}
  1. deep In-depth monitoring, monitoring 所有属性changes in objects;
    1. deep:trueWhen deep monitoring is enabled, any property value change will trigger deep monitoring;
    2. deep In-depth monitoring can only get the latest value;
    3. 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 时,刚载入页面时,也可监听数据的变化
}

Guess you like

Origin blog.csdn.net/qq_45050686/article/details/128108192