学习优先度:★★★☆☆

难易度:★★★☆☆

Vue 的 Composition API 允许您使用 watch 函数观察反应式数据,从而根据数据变化执行侧效应。

Vue Composition API 中的 watch 函数用于在所观察的反应数据发生变化时执行边效应。这对于诸如在参数发生变化时获取数据或执行验证等任务非常有用。

【代码示例】

// Import the reactive and watch functions from Vue
import { reactive, watch } from 'vue';
// Create a reactive object
const state = reactive({
 count: 0
});
// Watch the count property and log changes
watch(
 () => state.count,
 (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
 }
);
// Function to increment the count
function increment() {
 state.count++;
}
// Simulating a Vue component's setup function
function setup() {
 return {
  state,
  increment
 };
}
// Example of using the setup function
const { state, increment } = setup();
increment(); // count changed from 0 to 1
increment(); // count changed from 1 to 2

【执行结果】

count changed from 0 to 1
count changed from 1 to 2

观察函数允许你在所观察的数据发生变化时执行回调函数,从而对反应式数据的变化做出反应。在示例中,我们创建了一个反应式状态对象,并在state.count 上设置了一个观察器。在示例中,我们创建了反应式状态对象,并在 state.count 上设置了观察器。每当 state.count 发生变化时,观察器都会向控制台记录一条信息,同时显示新旧值。要有效使用观察器,就必须了解 Vue 反应式系统的细微差别,例如确保被观察的数据是正确的反应式数据,以及管理观察复杂数据结构对性能的影响。

【补充】

除了 watch 之外,Vue 还提供了 watchEffect,它可以立即运行给定函数并自动跟踪其依赖关系。这对于需要对变化做出反应而无需明确指定观察源的简单用例非常有用。