Watch data monitoring in vue and detailed explanation of each attribute in watch

The watch in vue mainly listens to the data数组 , yes对象值变化

1. Several methods of watch use

(1) Monitor the change of data data through watch, when the data changes, the current value will be printed

watch: {
    data(val, newval) {
        console.log(val)
        console.log(newval)
    }
}   

(2) Monitor the change of docData data through watch. When the data changes, this.change_number++ (using deep monitoring)

watch: {
    
    
    data: 'changeData' // 值可以为methods的方法名
}methods: {
    
    
    changeData(curVal,oldVal){
    
    
   conosle.log(curVal,oldVal)
  }
}

2. Explain the immediate, handler and deep attributes in watch in detail

(1) Immediate and handler
have a feature when using watch like this, that is, when the value is bound for the first time, the monitoring function will not be executed, only when the value changes. Properties are used if we need to 最初also execute a function when binding a value . E.g:需要immediate

watch: {
    
    
    docData: {
    
    
        handler(newVal) {
    
    
            this.change_number++
        },
        immediate: true
    }
}    

(2) Deep
When needed 监听一个对象的改变, the ordinary watch method cannot monitor the change of the internal properties of 此时就需要deep属性the object, and deeply monitor the object.

E.g:

data() {
    
    
    return {
    
    
        docData: {
    
    
            'doc_id': 1,
            'tpl_data': 'abc'
        }
    }
}watch: {
    
    
    docData: {
    
    
        handler(newVal) {
    
    
            this.change_number++
        },
    deep: true
    }    
}

Set deep: true to monitor the change of docData.doc_id. At this time, this listener will be added to all attributes of docData. 对象属性较多At that time , the handler will be executed for each attribute value change. If 只需要监听对象中的一个属性值, you can do the following optimization: use the form of a string to monitor object properties:

E.g:

data() {
    
    
    return {
    
    
        docData: {
    
    
            'doc_id': 1,
            'tpl_data': 'abc'
        }
    }
}watch: {
    
    
    'docData.doc_id': {
    
    
        handler(newVal, oldVal) {
    
    
             ......
        },
    deep: true
    }    
}

This will only add a listener to a specific property of the object

3. Summary

数组(One-dimensional, multi-dimensional) changes 不需要are deeply monitored, 对象and property changes of objects in the array are 需要deepdeeply monitored.

If you feel that the article is good, remember to pay attention, pay attention and collect it. Please correct me if there is any mistake. If you need to reprint, please indicate the source, thank you! ! !

Guess you like

Origin blog.csdn.net/m0_49714202/article/details/124466556