Vue watch
监听data数据
data() {
return {
frontPoints: 0
}
},
watch: {
frontPoints(newValue, oldValue) {
console.log(newValue)
}
}
监听数组
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
}
}
监听对象
data() {
return {
people: {
age: 53,
height: '55kg'
}
}
},
watch: {
people: {
handler(newValue, oldValue) {
console.log(newValue)
},
deep: true
}
}
只要people中的属性发生变化(可被监测到的),便会执行handler函数;
如果想监测具体的属性变化,则可以利用计算属性computed做中间层。
参考如下:
data() {
return {
people: {
age: 53,
height: '55kg'
}
}
},
computed: {
watchAge() {
return this.people.age
}
},
watch: {
watchAge(newValue, oldValue) {
console.log(newValue)
}
}