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

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>
http://www.xdnf.cn/news/1520.html

相关文章:

  • 金融软件测试有哪些注意事项?专业第三方软件测试服务机构分享
  • 【bug修复】一次诡异的接口数据显示 bug 排查之旅
  • JavaScript学习教程,从入门到精通,XMLHttpRequest 与 Ajax 请求详解(25)
  • Qt C++/Go/Python 面试题(持续更新)
  • Playwright 入门教程:从概念到应用(Java 版)
  • 协作开发攻略:Git全面使用指南 — 结语
  • windows上的RagFlow+ollama知识库本地部署
  • Spring Boot实战(三十六)编写单元测试
  • vuedraggable Sortable.js 实现拖拽排序功能VUE3
  • 4.2 Prompt工程与任务建模:高效提示词设计与任务拆解方法
  • 【Python网络爬虫实战指南】从数据采集到反反爬策略
  • HTML5 服务器发送事件 (Server-Sent Events):实现网页自动获取服务器更新
  • [论文阅读]REPLUG: Retrieval-Augmented Black-Box Language Models
  • 嵌入式:Linux系统应用程序(APP)启动流程概述
  • Qt 处理 XML 数据
  • 音视频之H.265/HEVC环路后处理
  • 国产紫光同创FPGA视频采集转SDI编码输出,基于HSSTHP高速接口,提供2套工程源码和技术支持
  • 模拟电路方向主要技术要点和大厂真题解析
  • 算法时代的“摩西十诫”:AI治理平台重构数字戒律
  • 理解npm的工作原理:优化你的项目依赖管理流程
  • express的中间件,全局中间件,路由中间件,静态资源中间件以及使用注意事项 , 获取请求体数据
  • 经验分享 | 如何高效使用 `git commit --amend` 修改提交记录
  • Android移动应用开发入门示例:Activity跳转界面
  • 【数据结构】Map与Set结构详解
  • React-组件通信
  • 【网络原理】从零开始深入理解TCP的各项特性和机制.(一)
  • 机器学习漏洞大汇总——利用机器学习服务
  • Scrapy框架爬虫官网的学习
  • 放爱心烟花
  • # 构建和训练一个简单的CBOW词嵌入模型