watch监听(数组或者对象)

时间:2019-06-12
本文章向大家介绍watch监听(数组或者对象),主要包括watch监听(数组或者对象)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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)
  }
}
5、watch和computed各自处理的数据关系场景不同

watch擅长处理的场景:一个数据影响多个数据
computed擅长处理的场景:一个数据受多个数据影响

6、method和computed触发条件不同
computed只提供了缓存的值,而没有重新计算
只有符合:1.存在依赖型数据 2.依赖型数据发生改变这两个条件,computed才会重新计算。
而methods下的数据,是每次都会进行计算的

引用源:
作者:乖乖果效36
链接:https://www.jianshu.com/p/29dc0c079949

原文地址:https://www.cnblogs.com/listen9436/p/11010004.html