vue要实现watch
Vue 中实现 watch 的方法
在 Vue 中,watch 用于监听数据的变化并执行相应的操作。以下是几种常见的实现方式:
基本用法
通过 watch 选项监听数据的变化,当数据变化时执行回调函数。
export default {
data() {
return {
message: 'Hello Vue'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed from', oldVal, 'to', newVal)
}
}
}
监听对象属性
如果需要监听对象的某个属性,可以使用点语法或字符串形式。
export default {
data() {
return {
user: {
name: 'John',
age: 25
}
}
},
watch: {
'user.name'(newVal, oldVal) {
console.log('Name changed from', oldVal, 'to', newVal)
}
}
}
深度监听
对于对象或数组,如果需要监听其内部属性的变化,可以设置 deep: true。
export default {
data() {
return {
user: {
name: 'John',
age: 25
}
}
},
watch: {
user: {
handler(newVal, oldVal) {
console.log('User object changed')
},
deep: true
}
}
}
立即触发
如果需要立即执行监听函数,可以设置 immediate: true。
export default {
data() {
return {
message: 'Hello Vue'
}
},
watch: {
message: {
handler(newVal, oldVal) {
console.log('Message is', newVal)
},
immediate: true
}
}
}
使用 $watch API
在组件实例中,可以通过 this.$watch 动态添加监听器。
export default {
data() {
return {
message: 'Hello Vue'
}
},
created() {
this.$watch('message', (newVal, oldVal) => {
console.log('Message changed from', oldVal, 'to', newVal)
})
}
}
监听多个数据
如果需要监听多个数据的变化,可以使用计算属性结合 watch。
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
}
},
watch: {
fullName(newVal, oldVal) {
console.log('Full name changed from', oldVal, 'to', newVal)
}
}
}
通过以上方法,可以灵活地监听 Vue 组件中数据的变化并执行相应的逻辑。







