momo's Blog.

Vue watch监听(数组或者对象)

字数统计: 294阅读时长: 1 min
2021/05/21 Share

前言

在看框架的时候,发现了这样的代码. 查看官方文档好像并没有讲到这个.

1
2
3
4
5
6
7
8
watch: {
$route: {
handler: function(route) {
this.redirect = route.query && route.query.redirect
},
immediate: true
}
},

watch 监听数组或者对象

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

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

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

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

  1. 普通的watch

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    data() {
    return {
      frontPoints: 0
    }
    },
    watch: {
    frontPoints(newValue, oldValue) {
      console.log(newValue)
    }
    }
  2. 数组的watch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)        
}
  }
}, 
}
}

参考

  1. watch监听(数组或者对象)
CATALOG
  1. 1. 前言
  2. 2. watch 监听数组或者对象
  3. 3. 参考