vue watch 实现方法
使用 watch 选项
在 Vue 组件的 watch 选项中定义侦听器,适用于直接监听数据属性或计算属性。
export default {
data() {
return {
count: 0
}
},
watch: {
count(newVal, oldVal) {
console.log(`count 从 ${oldVal} 变为 ${newVal}`);
}
}
}
监听对象属性
通过 deep 和 handler 监听对象或数组的深层变化。
watch: {
user: {
handler(newVal) {
console.log('user 对象发生变化', newVal);
},
deep: true // 深度监听
}
}
立即触发回调
使用 immediate: true 在初始化时立即执行侦听器。

watch: {
count: {
handler(newVal) {
console.log('初始值:', newVal);
},
immediate: true
}
}
使用 $watch API
在组件实例中动态添加侦听器,适合需要灵活控制的场景。
export default {
created() {
this.$watch('count', (newVal, oldVal) => {
console.log('动态监听 count:', newVal);
});
}
}
监听路由变化
在 Vue Router 中监听 $route 对象的变化。

watch: {
'$route'(to, from) {
console.log('路由从', from.path, '切换到', to.path);
}
}
监听计算属性
直接侦听计算属性的变化。
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
},
watch: {
fullName(newVal) {
console.log('全名更新为:', newVal);
}
}
取消侦听器
通过 $watch 返回的函数取消监听。
export default {
mounted() {
const unwatch = this.$watch('count', (newVal) => {
console.log('count:', newVal);
});
// 5秒后取消监听
setTimeout(unwatch, 5000);
}
}






