vue watch关于对象内的属性监听

374 阅读1分钟
原文链接: www.cnblogs.com

vue可以通过watch监听data内数据的变化。通常写法是:

?
1 2 3 4 5 6 7 8 9 data: {   a: 100 }, watch: {   a(newval, oldVal) {     // 做点什么。。。     console.log(newval, oldVal)   } }

vue监听整个对象,如下:

  • deep: true 深度监测
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 data: {   return {     msg: {       name: 'hahah',       color: 'red'     }   } } watch: {   msg: {     handler(newValue, oldValue) {       // 做点什么。。。       console.log(newValue)   },   deep: true }

如果监听对象内的某一具体属性,可以通过computed做中间层来实现:

?
1 2 3 4 5 6 7 8 9 10 11 computed: {   name() {     return this.msg.name   } }, watch:{   name(newValue, oldValue) {      // 做点什么。。。      console.log(newval, oldVal)   } }