实现vue中的watcher
实现 Vue 中的 Watcher
在 Vue 中,Watcher 用于监听数据变化并执行相应的回调函数。以下是实现 Watcher 的几种方法:
使用 watch 选项
在 Vue 组件中,可以通过 watch 选项监听数据的变化。当被监听的数据发生变化时,回调函数会被触发。

export default {
data() {
return {
message: 'Hello Vue'
}
},
watch: {
message(newVal, oldVal) {
console.log(`Message changed from ${oldVal} to ${newVal}`)
}
}
}
使用 $watch 方法
Vue 实例提供了 $watch 方法,可以在运行时动态添加 Watcher。这种方式适用于需要在特定条件下监听数据变化的场景。
export default {
data() {
return {
count: 0
}
},
created() {
this.$watch('count', (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`)
})
}
}
使用 immediate 和 deep 选项
immediate 选项允许 Watcher 在创建时立即执行回调函数。deep 选项用于深度监听对象或数组的变化。

export default {
data() {
return {
user: {
name: 'John',
age: 25
}
}
},
watch: {
user: {
handler(newVal, oldVal) {
console.log('User data changed')
},
deep: true,
immediate: true
}
}
}
使用计算属性与 Watcher 结合
计算属性可以依赖其他数据的变化,结合 Watcher 可以实现更复杂的逻辑。
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}`)
}
}
}
使用 vm.$watch 返回的取消函数
vm.$watch 返回一个取消观察的函数,可以在不需要监听时手动取消。
export default {
data() {
return {
temperature: 20
}
},
created() {
const unwatch = this.$watch('temperature', (newVal, oldVal) => {
console.log(`Temperature changed from ${oldVal} to ${newVal}`)
})
// 取消监听
setTimeout(() => {
unwatch()
}, 5000)
}
}
通过以上方法,可以灵活地实现 Vue 中的 Watcher 功能,满足不同场景下的数据监听需求。






