当前位置: 首页 > news >正文

Vue3 中 computed的详细用法

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({// getterget() {return firstName.value + ' ' + lastName.value},// setterset(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>

相关文章:

  • 达梦DMDSC初研
  • 【C语言】数据在内存中的存储:从整数到浮点数的奥秘
  • 1️⃣6️⃣three.js_光源
  • 大语言模型时代,单细胞注释也需要集思广益(mLLMCelltype)
  • 数字人接大模型第一步:表情同步
  • STM32 串口USART
  • 【嵌入式系统设计师(软考中级)】第二章:嵌入式系统硬件基础知识(2)
  • Concepts (C++20)
  • 如何在 Postman 中,自动获取 Token 并将其赋值到环境变量
  • 每日c/c++题 备战蓝桥杯 ([洛谷 P1226] 快速幂求模题解)
  • Java 富文本转word
  • java方法引用
  • static成员
  • jQuery的removeClass(),一次删除多个class
  • 4.2 Prompt工程与任务建模:高效提示词设计与任务拆解方法
  • 【学习笔记】文件包含漏洞--相关习题
  • 全面解析 UGC 平台物品冷启动策略
  • 【Linux内核】内核中的中断管理
  • Activepieces - 开源自动化工具
  • 【动手学大模型开发】什么是大语言模型
  • 李良生已任应急管理部党委委员、政治部主任
  • 最高法:侵犯著作权罪中的“复制发行”不包括单纯发行行为
  • 中国和阿塞拜疆签署互免签证协定
  • 印控克什米尔发生恐袭事件,外交部:中方反对一切形式的恐怖主义
  • 神舟十九号航天员乘组计划于4月29日返回东风着陆场
  • 受贿超8.22亿元,新疆维吾尔自治区党委原副书记李鹏新一审被判死缓