Vue3 中 computed的详细用法

发布于:2025-05-01 ⋅ 阅读:(61) ⋅ 点赞:(0)

Vue 3 中 computed 是一个非常重要的响应式 API,它是基于其依赖项的值来计算得出的值,当依赖项发生变化时,计算属性会自动更新

基本用法
  • 在选项式 API 中,computed 通常作为一个选项直接在组件的选项对象中定义。例如
<template>
   {{fullName}}
</template>

<script setup lang="ts">
import { ref ,computed} from 'vue'

const firstName = ref('su')
const lastName = ref('mu')
const fullName = computed(() => firstName.value  + lastName.value)
</script>

在这个例子中,fullName 是一个计算属性,它依赖于 firstName 和 lastName。当 firstName 或 lastName 发生变化时,fullName 会自动重新计算。

可写计算属性

  • 计算属性默认是只读的。当你尝试修改一个计算属性时,你会收到一个运行时警告。只在某些特殊场景中你可能才需要用到“可写”的属性,你可以通过同时提供 getter 和 setter 来创建
<script setup>
import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

const fullName = computed({
  // getter
  get() {
    return firstName.value + ' ' + lastName.value
  },
  // setter
  set(newValue) {
    // 注意:我们这里使用的是解构赋值语法
    [firstName.value, lastName.value] = newValue.split(' ')
  }
})
</script>

现在当你再运行 fullName.value = ‘John Doe’ 时,setter 会被调用而 firstName 和 lastName 会随之更新

计算属性缓存 vs 方法

  • 计算属性和方法都可以用于动态计算值,但它们在性能和使用场景上有一些关键的区别。主要区别在于缓存机制:计算属性具有缓存机制,而方法在每次触发时都会重新执行
<script setup>
import { reactive, computed } from 'vue'

const author = reactive({
  name: 'John Doe',
  books: [
    'Vue 2 - Advanced Guide',
    'Vue 3 - Basic Guide',
    'Vue 4 - The Mystery'
  ]
})

// 一个计算属性 ref
const publishedBooksMessage = computed(() => {
  return author.books.length > 0 ? 'Yes' : 'No'
})
// 组件中
function calculateBooksMessage() {
  return author.books.length > 0 ? 'Yes' : 'No'
}
</script>

<template>
  <p>Has published books:</p>
  <span>{{ publishedBooksMessage }}</span>
  <p>{{ calculateBooksMessage() }}</p>
</template>

若我们将同样的函数定义为一个方法而不是计算属性,两种方式在结果上确实是完全相同的,然而,不同之处在于计算属性值会基于其响应式依赖被缓存。一个计算属性仅会在其响应式依赖更新时才重新计算。这意味着只要 author.books 不改变,无论多少次访问 publishedBooksMessage 都会立即返回先前的计算结果,而不用重复执行 getter 函数

注意事项

  • 缓存机制 :computed 属性具有缓存机制,只有在它的依赖发生变化时才会重新计算,这使得它比普通函数更高效。如果你的计算逻辑不需要依赖响应式数据,或者希望每次访问都重新计算,那么不应该使用 computed,而是应该使用普通函数。
  • 与 watch 的区别 :computed 是基于它的依赖项进行懒计算的,只有在访问它的时候才会执行计算函数。而 watch 是主动监听响应式数据的变化,当监听的数据发生变化时,执行回调函数。

实际项目中的常用法

1. 使用多个响应式引用作为依赖
<script setup>
import { reactive, computed } from 'vue'

const user = reactive({
  profile: {
    name: 'Alice',
    addresses: [
      { city: 'New York', primary: true },
      { city: 'London', primary: false }
    ]
  }
})
// 计算主地址
const primaryAddress = computed(() => {
  return user.profile.addresses.find(addr => addr.primary) || {}
})

// 计算地址摘要
const addressSummary = computed(() => {
  return user.profile.addresses
    .map(addr => `${addr.city}${addr.primary ? ' (主)' : ''}`)
    .join(', ')
})
</script>
2.使用 computed 和 watch 结合
<script setup>
import { ref, computed, watch } from 'vue';
const username = ref('');
    const greeting = computed(() => {
      return `Hello, ${username.value}!`;
    });

    watch(greeting, (newGreeting, oldGreeting) => {
      console.log(`Greeting changed from "${oldGreeting}" to "${newGreeting}"`);
      // 在这里可以添加其他副作用逻辑
    });

</script>

3.使用 computed 进行条件渲染
<script setup>
import { ref, computed, watch } from 'vue';
const isDarkMode = ref(false);
const themeClass = computed(() => {
    return isDarkMode.value ? 'dark-theme' : 'light-theme';
});
</script>
4.使用 computed 进行数据过滤和排序
<script setup>
import { ref, computed, watch } from 'vue';
const products = ref([
      { name: 'Phone', price: 999, inStock: true },
      { name: 'Tablet', price: 799, inStock: false },
      { name: 'Laptop', price: 1299, inStock: true }
    ]);

const availableProducts = computed(() => {
    return products.value.filter(product => product.inStock);
});

const sortedProducts = computed(() => {
    return availableProducts.value.sort((a, b) => a.price - b.price);
});
</script>
5.使用 computed 处理表单输入
<script setup>
import { ref, computed, watch } from 'vue';
const rawInput = ref('');

const formattedInput = computed({
    get: () => {
    return rawInput.value;
    },
    set: (newValue) => {
    // 对输入进行转换,例如大写转换
    rawInput.value = newValue.toUpperCase();
    }
});
</script>

网站公告

今日签到

点亮在社区的每一天
去签到