vue实现watch
Vue 的 watch 实现方法
在 Vue 中,watch 用于监听数据变化并执行相应的回调函数。以下是几种常见的实现方式:
基本用法
通过选项式 API 的 watch 属性监听数据变化:
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed from', oldVal, 'to', newVal)
}
}
}
立即触发和深度监听
添加 immediate 和 deep 选项:

watch: {
user: {
handler(newVal, oldVal) {
console.log('User changed')
},
immediate: true,
deep: true
}
}
监听对象属性
使用字符串路径监听嵌套属性:
watch: {
'user.name'(newVal) {
console.log('Username changed to', newVal)
}
}
组合式 API 的 watch
在 setup() 中使用 watch 函数:

import { ref, watch } from 'vue'
export default {
setup() {
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log('Count changed from', oldVal, 'to', newVal)
})
return { count }
}
}
监听多个数据源
使用数组监听多个响应式数据:
watch(
[count, name],
([newCount, newName], [oldCount, oldName]) => {
console.log('Count or name changed')
}
)
停止监听
watch 函数返回停止函数:
const stop = watch(count, (newVal) => {
if (newVal > 10) {
stop()
}
})
watchEffect 替代方案
自动追踪依赖的响应式数据:
import { watchEffect } from 'vue'
watchEffect(() => {
console.log('Count is now:', count.value)
})
注意事项
- 深度监听 (
deep: true) 会对对象的所有属性进行递归监听,可能影响性能 - 数组变更需要通过深度监听或使用数组方法触发
- 对于大型对象,考虑监听特定属性而非整个对象
- 在组件卸载前,组合式 API 的
watch会自动停止,但也可手动停止






