vue watch对象或者数组的问题

普通的watch是这个样子的:

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

数组的watch是这个样的:

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
  }
}

对象的watch了是这个样子

data() {
  return {
    bet: {
      pokerState: 2342,
      pokerHistory: 'local'
    }   
    }
},
watch: {
  bet: {
    handler(newValue, oldValue) {
      console.log(newValue)
    },
    deep: true //是否深度监听
  }
}

但是如果仅仅这样的话只能监听到对象的变动, 是获取不到具体是哪个值发生变动的

机智的我们可以利用计算属性这个方法来处理问题,代码如下

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

猜你喜欢

转载自blog.csdn.net/daiwu4044/article/details/82531634
今日推荐