Vue3中的computed,watch,watchEffect如何使用

发布时间:2022-06-15 16:09:52 作者:iii
来源:亿速云 阅读:262

Vue3中的computed, watch, watchEffect如何使用

在Vue3中,computedwatchwatchEffect是三个非常重要的响应式API,它们可以帮助我们更好地管理和响应数据的变化。本文将详细介绍这三个API的使用方法和区别。

1. computed

computed用于创建一个计算属性,它会根据依赖的响应式数据自动更新。计算属性是基于它们的依赖进行缓存的,只有在依赖发生变化时才会重新计算。

基本用法

import { ref, computed } from 'vue';

const count = ref(0);
const doubleCount = computed(() => count.value * 2);

console.log(doubleCount.value); // 0

count.value = 1;
console.log(doubleCount.value); // 2

计算属性的setter

计算属性默认是只读的,但你可以通过提供一个setter来使其可写。

const count = ref(0);
const doubleCount = computed({
  get: () => count.value * 2,
  set: (newValue) => {
    count.value = newValue / 2;
  }
});

doubleCount.value = 4;
console.log(count.value); // 2

2. watch

watch用于监听一个或多个响应式数据的变化,并在变化时执行回调函数。watch可以监听refreactive对象、计算属性等。

基本用法

import { ref, watch } from 'vue';

const count = ref(0);

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

count.value = 1; // 输出: count changed from 0 to 1

监听多个数据源

你可以通过传递一个数组来监听多个数据源。

const count1 = ref(0);
const count2 = ref(0);

watch([count1, count2], ([newCount1, newCount2], [oldCount1, oldCount2]) => {
  console.log(`count1 changed from ${oldCount1} to ${newCount1}`);
  console.log(`count2 changed from ${oldCount2} to ${newCount2}`);
});

count1.value = 1; // 输出: count1 changed from 0 to 1
count2.value = 2; // 输出: count2 changed from 0 to 2

深度监听

默认情况下,watch是浅层监听的,如果你需要监听对象内部的变化,可以使用deep选项。

const state = reactive({ count: 0 });

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

state.count = 1; // 输出: state changed { count: 1 }

3. watchEffect

watchEffect是一个立即执行的监听器,它会自动追踪其内部使用的响应式数据,并在这些数据变化时重新执行。

基本用法

import { ref, watchEffect } from 'vue';

const count = ref(0);

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

count.value = 1; // 输出: count is 1

停止监听

watchEffect返回一个停止监听的函数,你可以在需要时调用它来停止监听。

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

count.value = 1; // 输出: count is 1

stop();

count.value = 2; // 不会输出

清理副作用

watchEffect的回调函数可以接收一个onInvalidate函数,用于清理副作用。

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

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

count.value = 1; // 1秒后输出: count is 1
count.value = 2; // 1秒后输出: count is 2

总结

根据不同的需求,选择合适的API可以帮助你更高效地管理Vue应用中的响应式数据。

推荐阅读:
  1. Vue3中watch如何使用
  2. vue3中watch和watchEffect怎么使用

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

vue3 computed watch

上一篇:Android Flutter如何实现有趣的页面滚动效果

下一篇:如何利用Python创建位置生成器

相关阅读

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

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