computed

Computed (computed properties), as the name implies, computes new properties through computation, dynamically calculates new properties based on dependent properties, and caches the results through the getters in ES6.

Code examples:

new vue({
    data:{
        n:1,
        m:2,
    },
    template:`
        <div>{{q}}</div>
    `,
    computed:{
        q() {return this.m+this.n
        }
    }
})
Copy the code

watch

“Watch” is used to listen for data. The listener has two parameters: value, oldValue, and executes a callback when the data is changed. If you want to listen for data in a deeper way, use “deep:true”. true

Code examples:

new vue({
    data:{
        q:{
          n:1,
          m:2,
        },
    },
    template:`
        <div>
            {{q.n}}
            <button @click="q.n += 1">n+1</button>
        </div>
    `,
    watch:{
        q:{
          handler(){
            console.log('the data has changed')
          },
          immediate:true,
          deep:true,}}})Copy the code

conclusion

Do not use watch for demands that can be solved with computed, use computed if the data depends on other data, and use Watch if you want to listen for changes in data.