The difference between computed properties and watch and their usage

1. Overview

Both computed and watch are properties in the Vue framework used to monitor data changes.

2. computed properties

1. The usage method is the same as the data in data, but it is similar to an execution method.
2. Do not add () when calling.
3. There must be a return return
. 4. If the attributes that the function depends on have not changed, read it from the cache.

Example
computed:{
    Total(){
        let price = 0;
        for (let i = 0;i<this.tableData.length;i++) {
            price += this.tableData[i].taxUnitPrice * this.tableData[i].invNum
        }
        this.detailedSend.total = price
        return price;
    },
},

3. watch monitoring

1. The function name of watch must be consistent with the data name in data.
2. The function in watch has two parameters. The former is newVal and the latter is oldVal.
3. The function in watch does not need to be called.
4. Watch will only listen. Whether the value of the data changes, instead of monitoring whether the address of the data changes. To monitor in depth, you need to use the deep: true attribute. 5. Immediate
: true does a monitoring when the page is first loaded.

Example
watch: {
    keyword () {
        const result = []
        this.jsonData.forEach(val => {
            if (val.name.indexOf(this.keyword) > -1) {
                result.push(val.name)
            }
        });
        this.cityList = result
    }
},

4. Difference

1. Function: computed is a calculated attribute; watch is to monitor changes in a value and execute the corresponding callback.
2. Whether to call the cache: the cache will be called when the attribute on which the computed function depends does not change; watch will be called every time the monitored value changes. Call the callback
3. Whether to call return: computed must be present; watch is optional
4. Usage scenarios: computed when one attribute is affected by multiple attributes; such as shopping cart product settlement; watch when one piece of data affects multiple pieces of data, such as Search box
5. Whether it supports asynchrony: computed function cannot have asynchrony; watch can

Guess you like

Origin blog.csdn.net/shanghai597/article/details/131912152