Vue学习记录之四(computed的用法)

ops/2024/9/19 14:14:22/ 标签: vue.js, 学习, 前端

computed 属性用于创建计算属性。计算属性是基于现有响应式数据派生出的值,它会自动缓存,只有当依赖的响应式数据发生变化时,计算属性才会重新计算,这样可以提高性能和避免不必要的重复计算。

书写有两种方法: 1、选项式写法,2、函数式写法

<template><div>: <input v-model="firstName" type="text" ></div><div>: <input v-model="lastName" type="text" ></div><div>: <input v-model="name" type="text" ></div><button @click="change">修改名字</button>
</template>
<script setup lang='ts'>
import { ref,reactive,computed } from 'vue'
let firstName = ref('张')
let lastName = ref('三')
//1.选项式写法支持一个对象传入get函数以及set函数自定义操作
/*
let name = computed<string>({get() {return firstName.value + "-" + lastName.value },set(newVal){console.log(newVal.split("-"));[firstName.value,lastName.value] = newVal.split("-")}
})
*/
//2.函数式写法 只能支持一个getter函数不允许修改值的
let name = computed(()=>firstName.value + '-' + lastName.value)const change = () =>{name.value = "赵-四"    //如果使用第二种用法,这里将会报错。
}
</script>

实战购物车,使用原始的方法实现

<template><div style="margin:auto"><table border width="600" cellpadding="0" cellspacing="0" center><thead><tr><th>名称</th><th>单价</th><th>数量</th><th>总价</th><th>操作</th></tr></thead><tbody><tr v-for="(item,index) in data"><td>{{item.name}}</td><td>{{item.price}}</td><td><button @click="item.num > 1 ? (item.num--,total()) : null">-</button>{{item.num}}<button @click="item.num > 99 ? null : (item.num++,total())">+</button></td><td>{{item.num * item.price}}</td><td><button @click="del(index)">删除</button></td></tr></tbody><tfoot><tr><td colspan="5">{{$total}}</td></tr></tfoot></table></div>
</template>
<script setup lang='ts'>
import { ref,reactive } from 'vue'
let $total = ref<number>(0)
interface Data{name: string,price: number,num: number
}
let data = reactive<Data[]>([{name: "张1",price: 50,num: 1},{name: "张2",price: 100,num: 2},{name: "张3",price: 150,num: 3},{name: "张4",price: 200,num: 4},
])
let total = () => {$total.value = data.reduce((prev:number,next:Data)=>{return prev + next.num * next.price},0)
}
total()
const del=(index:number)=>{data.splice(index,1)  //splice() 方法用于添加或删除数组中的元素total()
}
</script>

购物车加入computer函数带来的便捷

<template><div style="margin:auto"><table border width="600" cellpadding="0" cellspacing="0" center><thead><tr><th>名称</th><th>单价</th><th>数量</th><th>总价</th><th>操作</th></tr></thead><tbody><tr v-for="(item,index) in data"><td>{{item.name}}</td><td>{{item.price}}</td><td><button @click="item.num > 1 ? item.num-- : null">-</button>{{item.num}}<button @click="item.num > 99 ? null : item.num++">+</button></td><td>{{item.num * item.price}}</td><td><button @click="del(index)">删除</button></td></tr></tbody><tfoot><tr><td colspan="5">{{ total }}</td></tr></tfoot></table></div>
</template>
<script setup lang='ts'>
import { ref,reactive, computed } from 'vue'
interface Data{name: string,price: number,num: number
}
let data = reactive<Data[]>([{name: "张1",price: 50,num: 1},{name: "张2",price: 100,num: 2},{name: "张3",price: 150,num: 3},{name: "张4",price: 200,num: 4},
])
const total = computed(() => {return data.reduce((prev:number,next:Data)=>{return prev + next.num * next.price},0)
})const del=(index:number)=>{data.splice(index,1)  //splice() 方法用于添加或删除数组中的元素
}
</script>

购物车添加搜索功能

<template><input v-model="keyword" placeholder="搜索" type="text"><div style="margin:auto"><table border width="600" cellpadding="0" cellspacing="0" center><thead><tr><th>名称</th><th>单价</th><th>数量</th><th>总价</th><th>操作</th></tr></thead><tbody><tr v-for="(item,index) in searchData"><td>{{item.name}}</td><td>{{item.price}}</td><td><button @click="item.num > 1 ? item.num-- : null">-</button>{{item.num}}<button @click="item.num > 99 ? null : item.num++">+</button></td><td>{{item.num * item.price}}</td><td><button @click="del(index)">删除</button></td></tr></tbody><tfoot><tr><td colspan="5">{{ total }}</td></tr></tfoot></table></div>
</template>
<script setup lang='ts'>
import { ref,reactive, computed } from 'vue'
let keyword = ref<string>("")
interface Data{name: string,price: number,num: number
}
let data = reactive<Data[]>([{name: "张1",price: 50,num: 1},{name: "张2",price: 100,num: 2},{name: "张3",price: 150,num: 3},{name: "张4",price: 200,num: 4},
])
const total = computed(() => {return searchData.value.reduce((prev:number,next:Data)=>{return prev + next.num * next.price},0)
})
const searchData = computed(()=>{return data.filter((item:Data)=>{return item.name.includes(keyword.value)})
})
const del=(index:number)=>{data.splice(index,1)  //splice() 方法用于添加或删除数组中的元素
}
</script>

知识点:
1、在 TypeScript 中,type 和 interface 都可以用来定义对象的形状。
扩展性: interface 支持接口继承,可以通过 extends 关键字继承其他接口。接口可以多次声明并合并(声明合并)。实现: 类可以实现一个或多个接口,确保类符合接口的结构。
组合性: type 支持更多的类型组合操作,如联合类型、交叉类型等。它可以用于定义复杂的类型别名。
不可扩展: type 不能进行声明合并,定义后不能再扩展或重新声明。

2、reduce函数的使用
reduce()是JavaScript的数组方法之一,它接受一个回调函数作为其参数,并返回一个单一的值。该方法可用于
对数组的所有项进行迭代,并将它们合并为一个最终值。reduce()方法在处理Vue数组中的大量数据时非常有
用。

array.reduce(
callback(accumulator, currentValue, currentIndex, array),
initialValue
);
callback: 这是一个回调函数,作用是将数组中的每一个元素逐个处理。回调函数接收四个参数:

accumulator: 累加器,保存上一次调用回调函数时的返回值(即中间结果)。
currentValue: 数组中当前处理的元素。
currentIndex: 当前元素的索引(可选)。
array: 当前被遍历的数组(可选)。
initialValue: 可选参数,表示累加器的初始值。如果没有提供,reduce() 会将数组的第一个元素作为初始值,并从第二个元素开始迭代。

//1、计算数组中所有元素的总和 
const numbers = [1, 2, 3, 4, 5]; 
const sum = numbers.reduce(
(total, current) => total + current, 
0); 
console.log(sum); //输出:15
//2、求数组中的最大值
const numbers = [10, 5, 7, 20, 25]; 
const max = numbers.reduce((previous, current) => previous > current ? previous : current); 
console.log(max); //输出:25

3、filter 方法用于创建一个新数组,其中包含所有通过指定函数测试的元素。filter 不会改变原数组,而是返回一个新的数组。

let newArray = array.filter(callback(element[, index[, array]])[, thisArg])
/*
callback: 用来测试数组每个元素的函数,返回 true 表示保留该元素,返回 false 表示丢弃该元素。该函数接收三个参数:
element: 当前处理的元素。
index (可选): 当前处理元素的索引。
array (可选): 调用 filter 的原数组。
thisArg (可选): 执行 callback 时,用作 this 的值。
*/

实例

//实例1
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter(function(number) {return number > 10;
});
console.log(filteredNumbers);
// 输出: [12, 130, 44]
//实例2 使用箭头函数
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter(number => number > 10);
console.log(filteredNumbers);
// 输出: [12, 130, 44]
//实例3
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
const longWords = words.filter(word => word.length > 6);
console.log(longWords);
// 输出: ["exuberant", "destruction", "present"]//实例4
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter((number, index) => index % 2 === 0);
console.log(filteredNumbers);
// 输出: [5, 8, 44]

http://www.ppmy.cn/ops/113035.html

相关文章

Selenium with Python学习笔记整理(网课+网站)

本篇是根据学习网站和网课结合自己做的学习笔记&#xff0c;后续会一边学习一边补齐和整理笔记 官方学习网站在这获取&#xff1a; https://selenium-python.readthedocs.io/getting-started.html#simple-usage WEB UI自动化环境配置 (推荐靠谱的博客文章来进行环境配置,具…

Spring框架常见漏洞

文章目录 SpEL注入攻击Spring H2 Database Console未授权访问Spring Security OAuth2远程命令执行漏洞(CVE-2016-4977)Spring WebFlow远程代码执行漏洞(CVE-2017-4971)Spring Data Rest远程命令执行漏洞(CVE-2017-8046)Spring Messaging远程命令执行漏洞(CVE-2018-1270)Spring …

2024年最新版Vue3学习笔记

本篇文章是记录来自尚硅谷禹神2023年课程的学习笔记&#xff0c;不得不说禹神讲的是真的超级棒&#xff01; 文章目录 创建Vue3工程main.ts文件解析初始化项目写一个简单的效果 Vue3核心语法setup函数setup和选项式的区别setup语法糖指定组件名称 响应式数据ref函数定义基本类…

Qwen2-VL的微调及量化

一、Qwen2-VL简介 Qwen2-VL是Qwen-VL的升级版本&#xff0c;能力更强&#xff0c;性能全面提升。尤其是72B参数的版本更是取了惊人的成绩。它可以读懂不同分辨率和不同长宽比的图片&#xff0c;在 MathVista、DocVQA、RealWorldQA、MTVQA 等基准测试创下全球领先的表现&#xf…

Luban策划开源工具

一、Luban游戏配置解决方案&#xff0c;是一个强大、易用、优雅、稳定的游戏配置解决方案。它设计目标为满足从小型到超大型游戏项目的简单到复杂的游戏配置工作流需求。luban标准化了游戏配置开发工作流&#xff0c;可以极大提升策划和程序的工作效率。 二、核心特性&#xf…

AI在医学领域:医学AI的安全与隐私全面概述

随着技术的进步&#xff0c;软件系统在商业产品中扮演着越来越重要的角色&#xff0c;并在医疗领域变得不可或缺。人工智能&#xff08;AI&#xff09;和机器学习&#xff08;ML&#xff09;的发展已经彻底改变了现代医疗系统&#xff0c;为通过病人诊断、监测和医疗保健研究收…

C++初阶学习——探索STL奥秘——标准库中的queue与stack

1、适配器模式 STL 中的适配器可以分为三类: 从应用角度出发 容器适配器 container adapters 迭代器适配器 iterator adapters 仿函数适配器 functor adapters 其中&#xff0c;容器适配器可修改底层为指定容器 如由 vector 构成的栈、由 list 构成的队列 迭代器适配器…

-webkit-box-reflect属性与倒影效果的实现

-webkit-box-reflect 是一个非标准的 CSS 属性&#xff0c;主要用于在 WebKit 浏览器&#xff08;如 Chrome 和 Safari&#xff09;中创建元素的倒影效果。这个属性并不是 CSS 规范的一部分&#xff0c;但在实践中经常被用来实现简单而有趣的视觉效果。 基本语法 -webkit-box…

用于大数据分析的数据存储格式:Parquet、Avro 和 ORC 的性能和成本影响

高效的数据处理对于依赖大数据分析做出明智决策的企业和组织至关重要。显著影响数据处理性能的一个关键因素是数据的存储格式。本文探讨了不同存储格式(特别是 Parquet、Avro 和 ORC)对 Google Cloud Platform (GCP) 上大数据环境中查询性能和成本的影响。本文提供了基准测…

网页打开时,下载的文件fetcht类型?有什么作用?

‌fetch API‌是一种用于向服务器发送请求并获取响应的现代Web API。它支持获取各种类型的数据&#xff0c;包括文本、JSON、图像和文件等。fetch API的主要优势之一是支持流式传输和取消请求&#xff0c;这使得处理大型数据集和长时间运行的操作变得更加简单和可靠。此外&…

LinuxC高级作业1

1.已知网址www.hqyj.com截取出网址的每一个部分 2.整理思维导图 3.将配置桥接网络的过程整理成文档 i)) 保证虚拟机提供了桥接模式 菜单栏中 ----> 虚拟机 -----> 设置 -----> 网络适配器 ii) 保证虚拟机可以设置桥接网络 菜单栏中 ----> 编辑 -----> 虚拟网…

计算机人工智能前沿进展-大语言模型方向-2024-09-18

计算机人工智能前沿进展-大语言模型方向-2024-09-18 1. The Application of Large Language Models in Primary Healthcare Services and the Challenges W YAN, J HU, H ZENG, M LIU, W LIANG - Chinese General Practice, 2024 人工智能大语言模型在基层医疗卫生服务中的应…

python的基础语法

Python 的基础语法非常简洁明了&#xff0c;适合初学者快速上手。下面我将为你总结几个最重要的基础语法点&#xff0c;帮你快速掌握 Python 的核心概念。让我们从基础开始逐步深入&#xff0c;像刷副本一样一关一关地攻克它们&#xff01; 1. Hello, World! 每一种编程语言的…

【原创】java+springboot+mysql高校社团网系统设计与实现

个人主页&#xff1a;程序猿小小杨 个人简介&#xff1a;从事开发多年&#xff0c;Java、Php、Python、前端开发均有涉猎 博客内容&#xff1a;Java项目实战、项目演示、技术分享 文末有作者名片&#xff0c;希望和大家一起共同进步&#xff0c;你只管努力&#xff0c;剩下的交…

Linux相关概念和重要知识点(3)(yum、gcc、动静态库)

1.yum &#xff08;1&#xff09;yum是什么&#xff1f;有何背景&#xff1f; Linux是一个开源系统&#xff0c;人们可以在此基础上进行一些开发。有人开发一个项目&#xff0c;希望给更多人使用&#xff0c;于是将它编译成一个软件包&#xff08;不乏一些有趣的小软件&#…

【XR】AR HUD

1. AR HUD&#xff08;head up display&#xff09;原理 目标&#xff1a; 产业链上的各大Tier1及PGU企业都在积极开发这一技术&#xff0c;许多厂家已推出LCOS样机&#xff0c;比如说水晶光电、华阳集团、瀚思通、疆程已在北京车展或去年的上海车展上展出了LCOS方案的AR-HUD样…

基于Java、SpringBoot、Vue的加油站管理系统设计

摘要 本系统是一个基于Java、SpringBoot和Vue的加油站管理系统。它旨在提高加油站的运营效率&#xff0c;优化客户服务体验&#xff0c;并通过数据分析支持更精准的业务决策。该系统包括用户管理、汽油管理、站点管理等功能模块。通过这些功能&#xff0c;管理员可以方便地管理…

SpringBoot:解析excel

解析Excel文件&#xff0c;可以使用Apache POI库 <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version> </dependency> 上代码&#xff1a; /*** <b>Functio…

企业开发时,会使用sqlalchedmy来构建数据库 结构吗? 还是说直接写SQL 语句比较多?

企业开发时&#xff0c;会使用sqlalchedmy来构建数据库 结构吗&#xff1f; 还是说直接写SQL 语句比较多&#xff1f; 在企业开发中&#xff0c;是否使用SQLAlchemy来构建数据库结构&#xff0c;还是直接写SQL语句&#xff0c;这取决于项目的具体需求和开发团队的偏好。SQLAlc…

Stable Diffusion绘画 | 生成高清多细节图片的各个要素

在数字艺术领域&#xff0c;AI绘画技术已经逐渐成为艺术创作的新趋势。Stable Diffusion作为一款领先的AI绘画工具&#xff0c;以其生成高清多细节图片的能力备受关注。现在&#xff0c;让我们一起来探索Stable Diffusion生成高清多细节图片的各个要素&#xff0c;开启你的创意…