很多时候我们需要监听数据,可能是路由,类型可能会是字符串,数组,对象,整理了下几种监听的方式。
普通的 watch
data() { return { frontPoints: 0 } }, watch: { frontPoints(newValue, oldValue) { console.log(newValue) } }
数组的 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) } } }, deep: true } }
对象的 watch
data() { return { bet: { pokerState: 53, pokerHistory: 'local' } } }, watch: { bet: { handler(newValue, oldValue) { console.log(newValue) }, deep: true } }
只要 bet 中的属性发生变化(可被监测到的),便会执行 handler 函数;
如果想监测具体的属性变化,如 pokerHistory 变化时,才执行 handler 函数,则可以利用计算属性 computed 做中间层。
事例如下:
对象具体属性的 watch[活用 computed]
data() { return { bet: { pokerState: 53, pokerHistory: 'local' } } }, computed: { pokerHistory() { return this.bet.pokerHistory } }, watch: { pokerHistory(newValue, oldValue) { console.log(newValue) } }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于