Vue3 中 computed、watch、watchEffect 的使用方法

2025-01-10 20:32:30   小编

Vue3 中 computed、watch、watchEffect 的使用方法

在 Vue3 的开发过程中,computed、watch 和 watchEffect 是三个非常实用且强大的响应式 API,它们各自有着独特的应用场景和使用方式。

首先来看看 computed。computed 即计算属性,它是基于响应式依赖进行缓存的。当依赖项的值发生变化时,计算属性才会重新计算。例如,在一个电商购物车的组件中,我们可能有多个商品项,每个商品有单价和数量,我们需要计算购物车的总价。这时就可以使用 computed:

<template>
  <div>
    <p>总价: {{ totalPrice }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const products = ref([
  { price: 10, quantity: 2 },
  { price: 15, quantity: 1 }
]);

const totalPrice = computed(() => {
  let sum = 0;
  products.value.forEach(product => {
    sum += product.price * product.quantity;
  });
  return sum;
});
</script>

通过 computed,我们避免了重复计算,提高了性能。

接着是 watch。watch 用于观察一个或多个响应式数据源的变化,并在变化时执行回调函数。比如,当用户登录状态发生改变时,我们可能需要执行一些操作,如更新用户信息显示等。

<template>
  <div>
    <button @click="toggleLogin">登录/退出</button>
    <p v-if="isLoggedIn">欢迎回来!</p>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const isLoggedIn = ref(false);

watch(isLoggedIn, (newValue, oldValue) => {
  if (newValue) {
    // 模拟获取用户信息
    console.log('获取用户信息');
  } else {
    console.log('清除用户信息');
  }
});

const toggleLogin = () => {
  isLoggedIn.value =!isLoggedIn.value;
};
</script>

最后说说 watchEffect。watchEffect 会立即运行一个函数,并响应式追踪其依赖,当依赖变化时重新运行。它不需要像 watch 那样明确指定要监听的数据。例如,在一个实时显示当前时间的组件中:

<template>
  <div>
    <p>当前时间: {{ currentTime }}</p>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue';

const currentTime = ref('');

watchEffect(() => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString();
});
</script>

通过以上示例,我们能看到 computed、watch 和 watchEffect 在不同场景下发挥的作用,合理运用它们能极大提升 Vue3 应用开发的效率和质量。

TAGS: Vue3 watch watchEffect computed

欢迎使用万千站长工具!

Welcome to www.zzTool.com