vue3中的watch和watchEffect怎么用

发布时间:2022-05-17 13:43:22 作者:iii
来源:亿速云 阅读:403

Vue3中的watch和watchEffect怎么用

在Vue3中,watchwatchEffect是两个非常重要的响应式API,用于监听数据的变化并执行相应的操作。本文将详细介绍它们的用法和区别。

1. watch

watch用于监听一个或多个响应式数据的变化,并在数据变化时执行回调函数。它的基本语法如下:

import { watch, ref } from 'vue';

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
});

1.1 监听多个数据

watch可以同时监听多个数据源,只需将多个数据源放入一个数组中:

const count = ref(0);
const name = ref('Vue');

watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
  console.log(`count changed from ${oldCount} to ${newCount}`);
  console.log(`name changed from ${oldName} to ${newName}`);
});

1.2 深度监听

默认情况下,watch是浅层监听的,即只监听对象的第一层属性变化。如果需要深度监听对象的所有属性变化,可以设置deep选项为true

const state = reactive({
  user: {
    name: 'Vue',
    age: 3
  }
});

watch(
  () => state.user,
  (newValue, oldValue) => {
    console.log('user changed', newValue);
  },
  { deep: true }
);

1.3 立即执行

watch默认在数据变化时才会执行回调函数。如果希望在监听开始时立即执行一次回调函数,可以设置immediate选项为true

watch(
  count,
  (newValue, oldValue) => {
    console.log(`count changed from ${oldValue} to ${newValue}`);
  },
  { immediate: true }
);

2. watchEffect

watchEffect是一个更简洁的API,它会自动追踪回调函数中使用的响应式数据,并在这些数据变化时重新执行回调函数。它的基本语法如下:

import { watchEffect, ref } from 'vue';

const count = ref(0);

watchEffect(() => {
  console.log(`count is ${count.value}`);
});

2.1 自动追踪依赖

watchEffect会自动追踪回调函数中使用的所有响应式数据,因此不需要显式地指定监听的数据源。例如:

const count = ref(0);
const name = ref('Vue');

watchEffect(() => {
  console.log(`count is ${count.value}, name is ${name.value}`);
});

2.2 停止监听

watchEffect返回一个停止监听的函数,可以在需要时手动停止监听:

const stop = watchEffect(() => {
  console.log(`count is ${count.value}`);
});

// 停止监听
stop();

2.3 副作用清理

watchEffect的回调函数可以返回一个清理函数,用于在重新执行回调函数之前清理上一次的副作用:

watchEffect((onCleanup) => {
  const timer = setTimeout(() => {
    console.log(`count is ${count.value}`);
  }, 1000);

  onCleanup(() => {
    clearTimeout(timer);
  });
});

3. watch与watchEffect的区别

4. 总结

watchwatchEffect是Vue3中用于监听数据变化的两个重要API。watch更适合需要精确控制监听数据源的场景,而watchEffect则更适合自动追踪依赖并执行副作用的场景。根据实际需求选择合适的API,可以更高效地管理组件的响应式逻辑。

推荐阅读:
  1. Vue3中watch如何使用
  2. Vue3中watch的用法是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue3 watch watcheffect

上一篇:jquery动画函数有哪些

下一篇:python beautifulsoup4模块怎么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》