watch监听(数组或者对象)

4,704 阅读1分钟

handler:监听数组或对象的属性时用到的方法

deep:深度监听,为了发现对象内部值的变化,可以在选项参数中指定 deep:true 。注意监听数组的变动不需要这么做。

immediate: 在选项参数中指定 immediate: true 将立即以表达式的当前值触发回调

tips: 只要bet中的属性发生变化(可被监测到的),便会执行handler函数;如果想监测具体的属性变化,如pokerHistory变化时,才执行handler函数,则可以利用计算属性computed做中间层。

1 普通watch

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

2 数组的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)        
     }
  }
   }, 
  }
}

3 对象的watch

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

4 对象具体属性的watch[活用computed]

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

对于Computed:

  • 它支持缓存,只有依赖的数据发生了变化,才会重新计算
  • 不支持异步,当Computed中有异步操作时,无法监听数据的变化
  • 如果computed属性的属性值是函数,那么默认使用get方法,函数的返回值就是属性的属性值;在computed中,属性有一个get方法和一个set方法,当数据发生变化时,会调用set方法。

对于Watch:

  • 它不支持缓存,数据变化时,它就会触发相应的操作
  • 支持异步监听
  • 监听的函数接收两个参数,第一个参数是最新的值,第二个是变化之前的值