vue watch Simple Method Sample for Monitoring Objects

  • 2021-10-16 00:54:40
  • OfStack

What watch does: Listen for changes in data on an vue instance

Example:


queryData: {
name: '',
creator: '',
selectedStatus: '',
time: [],
},

1. Ordinary watch


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

2. watch of 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
    }
}

3. watch of the object


data() {
    return {
          bet: {
                pokerState: 53,
                pokerHistory: 'local'
          } 
 }
},
watch: {
    bet: {
          handler(newValue, oldValue) {
                console.log(newValue)
          },
          deep: true
    }
}

tips: The handler function is executed whenever the property in bet changes (which can be monitored);

If you want to monitor specific attribute changes, such as pokerHistory changes, before executing handler function, you can use the calculated attribute computed as the middle layer.
Examples are as follows:

4. watch for specific attributes of objects [use computed flexibly]


data() {
    return {
          bet: {
                pokerState: 53,
                pokerHistory: 'local'
          } 
 }
},
computed: {
    pokerHistory() {
          return this.bet.pokerHistory
    }
},
watch: {
    pokerHistory(newValue, oldValue) {
          console.log(newValue)
    }
}

Summarize


Related articles: