Use of watch in Vue

Vue watch

Monitor data

data() {
    
    
    return {
    
    
        frontPoints: 0    
    }
},
watch: {
    
    
    frontPoints(newValue, oldValue) {
    
    
        console.log(newValue)
    }
}

Monitor array

data() {
    
    
    return {
    
    
        winChips: new Array(11).fill(0)   
    }
},
watch: {
    
    
  winChips: {
    
    
    handler(newValue, oldValue) {
    
    
      for (let i = 0; i < newValue.length; i++) {
    
    
        if (oldValue[i] != newValue[i]) {
    
    
          console.log(newValue)
        }
      }
    },
    deep: true
  }
}

Listener

data() {
    
    
  return {
    
    
    people: {
    
    
      age: 53,
      height: '55kg'
    }   
    }
},
watch: {
    
    
  people: {
    
    
    handler(newValue, oldValue) {
    
    
      console.log(newValue)
    },
    deep: true
  }
}

As long as the attributes in people change (that can be monitored), the handler function will be executed;
if you want to monitor specific attribute changes, you can use the calculated attribute as an intermediate layer.
The reference is as follows:

data() {
    
    
  return {
    
    
    people: {
    
    
      age: 53,
      height: '55kg'
    }   
    }
},
computed: {
    
    
  watchAge() {
    
    
    return this.people.age
  }
},
watch: {
    
    
  watchAge(newValue, oldValue) {
    
    
    console.log(newValue)
  }
}

Guess you like

Origin blog.csdn.net/vigorZ/article/details/105688302