vue中watch监听

发布时间 2023-06-13 15:06:09作者: 鱼儿游上天

1.对data中一般数据的监听,使用watch,回调有newValue和oldValue两个参数, 当数据变化后触发

watch: {
  /**
     * data中数据的监听
     * @param newValue
     * @param oldValue
     */
  value: function (newValue, oldValue) {
    alert('监听' + oldValue + '变为' + newValue)
  },

2.对data中对象的监听,有三种方式

  1. 使用watch中的handler和deep对整个对象进行监听,当对象中某一个属性修改后变化
    valueObject: {
      handler (newValue, oldValue) {
        alert(newValue.item1)
      },
      deep: true
    },
  2. 直接对对象中的属性进行监听格式如下
    'valueObject.item1' (newValue, oldValue) {
      alert(newValue)
    },
  3. 通过computed作为中间变量进行监听

    computed: {
      getItem1 () {
        return this.valueObject.item1
      }
    },
    watch: {
      getItem1 (newValue, oldValue) {
        alert(newValue)
      }

3.对数组的监听

对数组的监听可以采用对象监听的第一种方式

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