vue实现watch
Vue 中实现 watch 的方法
在 Vue 中,watch 用于监听数据的变化并执行相应的回调函数。以下是几种常见的实现方式:
使用选项式 API 的 watch
在选项式 API 中,可以直接在组件的 watch 选项中定义监听器。监听器可以是一个函数,也可以是一个包含 handler 和 immediate、deep 等配置的对象。
export default {
data() {
return {
count: 0,
user: {
name: 'John',
age: 25
}
}
},
watch: {
// 监听简单数据
count(newVal, oldVal) {
console.log(`count changed from ${oldVal} to ${newVal}`);
},
// 监听对象属性
'user.name': {
handler(newVal, oldVal) {
console.log(`user.name changed from ${oldVal} to ${newVal}`);
},
immediate: true // 立即触发一次
},
// 深度监听对象
user: {
handler(newVal, oldVal) {
console.log('user object changed', newVal);
},
deep: true // 深度监听
}
}
}
使用组合式 API 的 watch
在组合式 API 中,可以通过 watch 函数来实现监听。watch 函数接受一个响应式引用或一个 getter 函数作为监听源,以及一个回调函数。
import { ref, watch, reactive } from 'vue';
export default {
setup() {
const count = ref(0);
const user = reactive({
name: 'John',
age: 25
});
// 监听 ref
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
// 监听 reactive 对象的属性
watch(
() => user.name,
(newVal, oldVal) => {
console.log(`user.name changed from ${oldVal} to ${newVal}`);
}
);
// 深度监听 reactive 对象
watch(
() => user,
(newVal, oldVal) => {
console.log('user object changed', newVal);
},
{ deep: true }
);
return {
count,
user
};
}
}
使用 watchEffect
watchEffect 是另一种监听方式,它会立即执行一次回调函数,并自动追踪回调函数中使用的响应式依赖。当依赖发生变化时,回调函数会再次执行。
import { ref, watchEffect, reactive } from 'vue';
export default {
setup() {
const count = ref(0);
const user = reactive({
name: 'John',
age: 25
});
watchEffect(() => {
console.log(`count is ${count.value}`);
console.log(`user.name is ${user.name}`);
});
return {
count,
user
};
}
}
监听多个数据源
可以通过数组形式监听多个数据源,回调函数会接收到一个包含新值和旧值的数组。
import { ref, watch } from 'vue';
export default {
setup() {
const count = ref(0);
const name = ref('John');
watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
console.log(`count changed from ${oldCount} to ${newCount}`);
console.log(`name changed from ${oldName} to ${newName}`);
});
return {
count,
name
};
}
}
停止监听
在组合式 API 中,watch 和 watchEffect 会返回一个停止监听的函数,调用该函数可以停止监听。

import { ref, watch } from 'vue';
export default {
setup() {
const count = ref(0);
const stop = watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
// 停止监听
stop();
return {
count
};
}
}
通过以上方法,可以根据实际需求选择合适的监听方式,灵活地监听数据变化并执行相应的操作。






