Vue WatchEffect函数创建高级侦听器

WatchEffect高级侦听器

在 Vue 3 中,我们可以使用 watchEffect 函数来创建高级侦听器。与 watchcomputed 不同,watchEffect 不需要指定依赖项,它会自动追踪响应式状态的变化,并在变化时重新运行。

使用 watchEffect 函数

下面是一个简单的示例,使用 watchEffect 函数来侦听一个响应式状态,并在状态变化时输出一条消息:

import { reactive, watchEffect } from 'vue';
const state = reactive({
  count: 0,
});
watchEffect(() => {
  console.log(`Count is now: ${state.count}`);
});
// 改变状态,输出 Count is now: 1
state.count++;

在上面的示例中,我们使用 reactive 函数来创建一个响应式对象 state,并使用 watchEffect 函数来创建一个侦听器。watchEffect 函数接受一个函数作为参数,这个函数会被自动运行,并在其中使用响应式状态。当其中任何一个响应式状态发生变化时,这个函数会被重新运行。

停止侦听

watchcomputed 不同,watchEffect 函数不会返回一个停止侦听的函数。如果我们需要停止侦听,我们可以将 watchEffect 的返回值设为 null,例如:

import { reactive, watchEffect } from 'vue';
const state = reactive({
  count: 0,
});
const stop = watchEffect(() => {
  console.log(`Count is now: ${state.count}`);
});
// 改变状态,输出 Count is now: 1
state.count++;
// 停止侦听
stop();

在上面的示例中,我们将 watchEffect 的返回值保存到一个变量 stop 中,然后在需要停止侦听时调用这个函数。

侦听多个状态

如果需要侦听多个响应式状态,我们可以在 watchEffect 函数中使用这些状态,并在函数中返回一个计算值,例如:

import { reactive, watchEffect } from 'vue';
const state = reactive({
  count1: 0,
  count2: 0,
});
watchEffect(() => {
  const sum = state.count1 + state.count2;
  console.log(`Sum is now: ${sum}`);
});
// 改变状态,输出 Sum is now: 1
state.count1++;
// 改变状态,输出 Sum is now: 3
state.count2 += 2;

在上面的示例中,我们使用 reactive 函数创建一个响应式对象 state,并在 watchEffect 函数中使用了 state.count1state.count2 两个响应式状态,然后计算了这两个状态的和,并输出了这个和。

懒执行

computed 类似,watchEffect 函数也支持懒执行(lazy evaluation)。如果我们将 watchEffect 的第二个参数设置为 { lazy: true },则这个函数会在第一次访问响应式状态时才会被运行,例如:

import { reactive, watchEffect } from 'vue';
const state = reactive({
  count: 0,
});
watchEffect(
  () => {
    console.log(`Count is now: ${state.count}`);
  },
  { lazy: true }
);
// 访问状态,输出 Count is now: 1
state.count++;

在上面的示例中,我们将 watchEffect 的第二个参数设置为 { lazy: true },然后在代码中访问了响应式状态 state.count。这时,watchEffect 中的函数才会被运行。

总结

watchEffect 函数是 Vue 3 中的一个新特性,它可以用来创建高级侦听器,自动追踪响应式状态的变化,并在变化时重新运行。与 watchcomputed 不同,watchEffect 不需要指定依赖项,它会自动追踪响应式状态的变化。如果需要停止侦听,我们可以将 watchEffect 的返回值设为 null。如果需要侦听多个响应式状态,我们可以在 watchEffect 函数中使用这些状态,并在函数中返回一个计算值。watchEffect 函数也支持懒执行(lazy evaluation),可以在第一次访问响应式状态时才会被运行。

原文地址:https://blog.csdn.net/to_the_Future/article/details/129408957