The literal distinction

  • computedCalculate attributeIt dynamically displays new results based on the data you rely on
  • watchIs a rightdataThe data ofListen to the callbackWhen rely ondataWhen the data changes, a callback function is executed. Is passed in the callbacknewValoldValTwo parameters.

Respective roles

computed

new Vue({
  el: '#app'.data: {
    message: 'hello'
  },
  template: ` < div > < p > the original string: "{{message}}" < / p > < p > reverse string: "{{computedMessage}}" < / p > < / div > `.computed: {
    // Calculates the getter for the property
    computedMessage: function () {
      // 'this' points to the VM instance
      return this.message.split(' ').reverse().join(' ')}}})// Original string: "hello"
// Reverse string: "olleh"
Copy the code

The value of the computedMessage is computed by message.split(” “).reverse().join(” “). The computedMessage does not need parentheses and can be directly used as an attribute and displayed on the page

let id = 0;
const createUser = (name, gender) = > {
    id += 1;
    return { id: id, name: name, gender: gender };
};
new Vue({
    data() {
        return {
            users: [
                createUser("All"."Male"),
                createUser("Yuan yuan"."Female"),
                createUser("Small new"."Male"),
                createUser("Little kwai"."Female")].gender: ""
        };
    },
    computed: {
        displayUsers() {
            const hash = {
                male: "Male".female: "Female"
            };
            const { users, gender } = this;
            if (gender === "") {
                return users;
            } else if (typeof gender === "string") {
                return users.filter(u= > u.gender === hash[gender]);
            } else {
                throw new Error("The value of gender is an unexpected value."); }}},methods: {
        setGender(string) {
            this.gender = string; }},template: '
      
< button@click ="setGender(')"> All male women < / button > < / div > < ul > < li v - for = "(u, index) in displayUsers" : the key = "index" > {{u.n ame}} - {{u.gender}}
`
}).$mount("#app"); Copy the code

When clicking different buttons, the calculation results will change and the page will be updated after recalculation.

The results of a calculated property are cached and the calculated property is recalculated only if its associated dependencies change. So when you click the same button again, you won’t recalculate because the result is the same.

watch

  • Execute a function when data changes

  • The Watch property can be a string, a function, an object, an array

  • Has the deep, immediate attributes

new Vue({
  data: {
    n: 0.obj: {
      a: "a"}},template: ` 
      
.watch: { n() { console.log(Changed "n"); }, obj() { console.log("Obj changed"); }, "obj.a": function() { console.log("Obj. A changed"); } } }).$mount("#app"); // Click "n+1" to get "n changed" // click "obj. A +hi" to get "obj. A changed" // Click "obj= new object ", get "obj changed" Copy the code

  • Note: when OBj. A changes, OBj does not change; When OBj changes, OBJ. A does not change

  • Guess: Watch listens for simple data types for values and complex data types (objects) for addresses

deep
  • So if you want to use a wireobj, can also be foundobj.aCan change be achieved?
// This can be done with deep
watch: {
    n() {
        console.log(Changed "n");
    },
    obj: {
        handler(){
            console.log("Obj changed");
        },
        deep: true
    },
    "obj.a": function() {
        console.log("Obj. A changed");
    }
    }
}).$mount("#app");
  
  // click "obj= new object ", get "obj changed ", "obj. A changed"
Copy the code
immediate

Specifying immediate: true in the option argument triggers the callback immediately with the current value of the expression

conclusion

  1. If a piece of data depends on other data, design it for computed

  2. If you need to do something when a data change, use Watch to observe the data change

P: Watch can perform asynchronous but computed cannot

This article references excerpts:

  1. The difference between computed and Watch in Vue — a pipe dream
  2. Brief introduction to the difference between computed and Watch in Vue – user 7118714082313
  3. Interview question: The difference between computed and Watch in Vue — the nostalgia of flying spin
  4. $watch
  5. The difference between computed and Watch in Vue –Jacky