深入解析Vue Composition API的watch()方法 - Netlify

作者:API传播员 · 2025-12-21 · 阅读时间:6分钟
本文深入解析Vue Composition API的watch()方法,涵盖监视ref和reactive数据、处理数组和对象的最佳实践,包括使用lodash的cloneDeep方法进行深度克隆和watchEffect的对比,帮助开发者高效管理数据变化和响应式交互。

Watch API简介

Vue 的 Watch API 是 Vue Composition API 的重要组成部分。它需要一个数据源和一个回调函数,当数据源发生变化时,回调函数会被触发执行。

在实际开发中,当需要跟踪响应式数据的变化并执行相应操作时,计算属性通常是一个不错的选择。然而,与 Options API 类似,Vue Composition API 提供了 watch 方法,为开发者提供了另一种观察和响应数据变化的方式。

需要注意的是,watch 的行为会因数据类型的不同而有所差异。如果你对它不熟悉,可能会感到困惑。在本文中,我们将深入探讨如何在处理 refreactive 状态,以及数组和对象时使用 watch 方法。


Watch API参考

使用 Watch API 时,需要传入两个参数:

  1. 数据源:需要监视的目标数据。
  2. 回调函数:当数据发生变化时,执行的副作用函数。

监视单个 ref

Watch API 支持监视单个 ref 或多个 ref。以下是监视简单数据类型(如字符串、数字、布尔值)的示例:

import { ref, watch } from 'vue';

const name = ref('John');watch(name, (newValue, oldValue) => {
  console.log('新值:', newValue);
  console.log('旧值:', oldValue);
});

在这个例子中,我们监视了 name 的变化,当值发生变化时,回调函数会被触发,记录新值和旧值。对于布尔值和数字类型的 ref,使用方式相同。


监视数组

当监视更复杂的数据类型(如数组)时,需要注意以下两点:

  1. 使用函数返回需要监视的数组。
  2. 返回数组的副本,而不是直接传递原始数组。
import { ref, watch } from 'vue';

const levels = ref([1, 2, 3]);watch(() => [...levels.value], (newValue, oldValue) => {
  console.log('新数组:', newValue);
  console.log('旧数组:', oldValue);
});

监视对象

对于对象类型的数据,可以直接传递对象到 Watch API 中,而无需像数组那样返回副本。

import { ref, watch } from 'vue';

const user = ref({ name: 'John', age: 30 });watch(user, (newValue, oldValue) => {
  console.log('新对象:', newValue);
  console.log('旧对象:', oldValue);
});

需要注意的是,对于数组和对象,newValueoldValue 的值可能相同。这是因为 Vue 默认不会深度比较数据。


监视嵌套对象或数组

当需要监视嵌套的对象或数组时,可以使用 lodashcloneDeep 方法来深度克隆数据:

import { ref, watch } from 'vue';
import cloneDeep from 'lodash/cloneDeep';

const nestedArray = ref([[1, 2], [3, 4]]);watch(() => cloneDeep(nestedArray.value), (newValue, oldValue) => {
  console.log('新嵌套数组:', newValue);
  console.log('旧嵌套数组:', oldValue);
});

通过这种方式,可以有效地跟踪嵌套数据的变化。


同时监视多个 ref

如果需要同时监视多个数据,可以通过数组将它们传递给 Watch API:

import { ref, watch } from 'vue';

const firstName = ref('John');
const lastName = ref('Doe');watch([firstName, lastName], ([newFirstName, newLastName], [oldFirstName, oldLastName]) => {
  console.log('新名字:', newFirstName, newLastName);
  console.log('旧名字:', oldFirstName, oldLastName);
});

使用 reactive 监视 API

与监视 ref 数据类似,Watch API 也可以用于监视 reactive 数据。以下是一些示例:


监视 reactive 数组

import { reactive, watch } from 'vue';
import cloneDeep from 'lodash/cloneDeep';

const levels = reactive([1, 2, 3]);watch(() => cloneDeep(levels), (newValue, oldValue) => {
  console.log('新数组:', newValue);
  console.log('旧数组:', oldValue);
});

在这里,我们使用了 lodashcloneDeep 方法来深度克隆数组,从而确保能够正确监视其变化。


监视嵌套的 reactive 数组

对于深度嵌套的数组,可以使用相同的方法:

import { reactive, watch } from 'vue';
import cloneDeep from 'lodash/cloneDeep';

const nestedArray = reactive([[1, 2], [3, 4]]);watch(() => cloneDeep(nestedArray), (newValue, oldValue) => {
  console.log('新嵌套数组:', newValue);
  console.log('旧嵌套数组:', oldValue);
});

监视 reactive 对象

对于对象类型的数据,监视方式与 ref 类似:

import { reactive, watch } from 'vue';
import cloneDeep from 'lodash/cloneDeep';

const user = reactive({ name: 'John', age: 30 });watch(() => cloneDeep(user), (newValue, oldValue) => {
  console.log('新对象:', newValue);
  console.log('旧对象:', oldValue);
});

深度监视

Watch API 提供了一个 deep 选项,可以用于深度监视嵌套数据:

import { reactive, watch } from 'vue';

const state = reactive({ user: { name: 'John', age: 30 } });watch(state, (newValue, oldValue) => {
  console.log('新状态:', newValue);
  console.log('旧状态:', oldValue);
}, { deep: true });

然而,deep 选项不会同时跟踪旧值和新值,因此在处理复杂数据时,lodash 的深度克隆方法仍然是更好的选择。


监视特定属性

如果只需要监视对象中的某个属性,可以通过返回该属性的匿名函数实现:

import { reactive, watch } from 'vue';

const user = reactive({ name: 'John', age: 30 });watch(() => user.name, (newValue, oldValue) => {
  console.log('新名字:', newValue);
  console.log('旧名字:', oldValue);
});

了解 watchEffect

watchEffect 是 Watch API 的另一种形式,它只需要一个回调函数作为参数。当回调函数中的任何依赖项发生变化时,watchEffect 会立即执行并重新运行。

import { ref, watchEffect } from 'vue';

const count = ref(0);watchEffect(() => {
  console.log('计数值:', count.value);
});

总结

本文详细解析了 Vue Composition API 中的 watch 方法,包括如何监视 refreactive 数据,以及处理数组、对象和嵌套数据的最佳实践。通过合理使用 watchwatchEffect,可以更高效地管理数据变化并响应用户交互。

原文链接: https://www.netlify.com/blog/2021/01/29/deep-dive-into-the-vue-composition-apis-watch-method/