person github
watchEffect
is a Composition API function in Vue 3, used to run a function immediately and track its dependencies responsively. The function is automatically re-run when a dependency (reactive reference or computed property) changes.
This is somewhat different from Vue 2 watch
, as it watch
is typically used to observe a single reactive property or computed property, while watchEffect
multiple reactive dependencies can be tracked automatically.
Basic usage
import {
ref, watchEffect } from 'vue';
export default {
setup() {
const count = ref(0);
const doubled = ref(0);
watchEffect(() => {
console.log(`count is: ${
count.value}`); // 自动追踪 count
doubled.value = count.value * 2; // 自动追踪 doubled
});
return {
count,
doubled
};
}
}
In this example, watchEffect
it is run once immediately and re-run whenever count
or doubled
changes.
stop observing
watchEffect
Returns a function to stop observing. You can call this function to stop observing:
const stopWatch = watchEffect(() => {
// 你的代码
});
// 停止观察
stopWatch();
watch
Comparison with
watchEffect
More automatic and convenient because it automatically tracks all reactive dependencies.watch
More flexible as it allows you to observe a single reactive reference or computed property and provide the old and new values.
Which one you choose depends on your specific needs. If you need more control and flexibility, you might choose watch
. If you want a simpler and automatic solution, this watchEffect
might suit you better.