学习优先度:★★★★☆
难易度:★★★☆☆
Vue 的 Composition API 允许您使用 watchEffect 函数来跟踪反应效果,该函数会在一段代码的反应依赖关系发生变化时自动重新运行该代码。
下面是一个简单的示例,演示如何使用 watchEffect 跟踪反应状态的变化。
【代码示例】
import { ref, watchEffect } from 'vue';
export default {
setup() {
// Create a reactive state variable
const count = ref(0);
// Track changes in the reactive state variable
watchEffect(() => {
console.log(`Count has changed to: ${count.value}`);
});
// Function to increment the count
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
};
【执行结果】
textCount has changed to: 0
Count has changed to: 1
Count has changed to: 2
...
在本例中,ref 被用来创建一个反应状态变量 count。watchEffect 函数接收一个回调,将 count 的当前值记录到控制台。每次 count.value 发生变化时,都会重新执行回调,打印新值。增量函数演示了如何改变反应状态,触发 watchEffect 回调。
【补充】
watchEffect 对于应与反应状态变化自动同步的副作用非常有用。它与计算属性类似,但更加灵活,因为它可以执行任意的副作用,如记录日志、获取数据或更新 DOM。