阅读 128

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)
  }
}复制代码

对于Computed:

  • 它支持缓存,只有依赖的数据发生了变化,才会重新计算

  • 不支持异步,当Computed中有异步操作时,无法监听数据的变化

  • 如果computed属性的属性值是函数,那么默认使用get方法,函数的返回值就是属性的属性值;在computed中,属性有一个get方法和一个set方法,当数据发生变化时,会调用set方法。

对于Watch:

  • 它不支持缓存,数据变化时,它就会触发相应的操作

  • 支持异步监听

  • 监听的函数接收两个参数,第一个参数是最新的值,第二个是变化之前的值


作者:有怪兽
链接:https://juejin.cn/post/6989127303632519204


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐