深入解析Vue Composition API的watch()方法 - Netlify
Watch API简介
Vue 的 Watch API 是 Vue Composition API 的重要组成部分。它需要一个数据源和一个回调函数,当数据源发生变化时,回调函数会被触发执行。
在实际开发中,当需要跟踪响应式数据的变化并执行相应操作时,计算属性通常是一个不错的选择。然而,与 Options API 类似,Vue Composition API 提供了 watch 方法,为开发者提供了另一种观察和响应数据变化的方式。
需要注意的是,watch 的行为会因数据类型的不同而有所差异。如果你对它不熟悉,可能会感到困惑。在本文中,我们将深入探讨如何在处理 ref 和 reactive 状态,以及数组和对象时使用 watch 方法。
Watch API参考
使用 Watch API 时,需要传入两个参数:
- 数据源:需要监视的目标数据。
- 回调函数:当数据发生变化时,执行的副作用函数。
监视单个 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,使用方式相同。
监视数组
当监视更复杂的数据类型(如数组)时,需要注意以下两点:
- 使用函数返回需要监视的数组。
- 返回数组的副本,而不是直接传递原始数组。
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);
});
需要注意的是,对于数组和对象,newValue 和 oldValue 的值可能相同。这是因为 Vue 默认不会深度比较数据。
监视嵌套对象或数组
当需要监视嵌套的对象或数组时,可以使用 lodash 的 cloneDeep 方法来深度克隆数据:
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);
});
在这里,我们使用了 lodash 的 cloneDeep 方法来深度克隆数组,从而确保能够正确监视其变化。
监视嵌套的 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 方法,包括如何监视 ref 和 reactive 数据,以及处理数组、对象和嵌套数据的最佳实践。通过合理使用 watch 和 watchEffect,可以更高效地管理数据变化并响应用户交互。
原文链接: https://www.netlify.com/blog/2021/01/29/deep-dive-into-the-vue-composition-apis-watch-method/
最新文章
- Google DeepMind发布 Genie 3与Shopify:2小时上线电商3D样板间实战
- FLUX.1 Kontext API 使用完全指南:解锁文本驱动的智能图像编辑
- 如何防范User-Agent信息伪装引发的API访问风险
- 苹果支付流程:从零开始的接入指南
- 全面掌握 OpenAPI 规范:定义、生成与集成指南
- 深入解析granularity是什么?颗粒度中文详解
- Deribit API – 入门指南
- REST API命名规范的终极指南:清晰度和一致性的最佳实践
- Go:基于 MongoDB 构建 REST API — Fiber 版
- 免费IP地址查询API接口推荐
- 【2025】AI 占星报告批量生成器|基于 Astro-Seek API 微调 7B 模型,一键输出每日/每周运势
- 微信API接口调用凭证+Access token泄露