uni-app学习笔记十--vu3 computed的运用(二)

在商城类项目中,经常需要根据用户选中的商品动态计算总价,此时可以使用computed计算属性动态计算。先来看效果:

下面是代码实现:

需要注意的是,vue中checked选中的值须为字符串类型,所以下面的id声明为字符串类型而不是整型。

html 复制代码
<template>
	<view class="out">
		<checkbox-group @change="itemChange">
			<view class="item" v-for="(item,index) in goods" :key="item.id">
				<checkbox :value="item.id" :checked=item.checked></checkbox>
				<text class="title">{{item.name}}</text>
				<text class="price">{{item.price}}元</text>
				<text class="del" @click="remove(index)">删除</text>
			</view>
		</checkbox-group>
		<view class="card">
			<view class="text">
				总共选择了{{selectedItems.length}}件商品,总价是{{totalPrice}}元
			</view>
		</view>
		
	</view>
</template>

<script setup>
	import {computed, ref} from "vue"
	const goods = ref(
	[
		{"id":"1","name":"Apple",price:8999,checked:false},
		{"id":"2","name":"华为",price:3899,checked:false},
		{"id":"3","name":"小米",price:1999,checked:false},
		{"id":"4","name":"oppon",price:1699,checked:false},
	])
	const selectedItems = ref([])
	const totalPrice = computed(()=>{
	  return goods.value.filter(item=>item.checked).reduce((prev,curr)=>prev+curr.price,0)
	})
	function remove(index){
		goods.value.splice(index,1)
	}
	function itemChange(e){
		selectedItems.value=e.detail.value
		goods.value.forEach(item=>{
			item.checked=selectedItems.value.includes(item.id)
		})
	}
	
</script>

<style lang="scss">
	  .out{
		  padding: 10px;
		  .item{
			  padding: 10px 0;
			  .price{
				  margin-left: 30px;
			  }
			  .del{
				  color:#c00;
				  margin-left: 30px;
			  }
	    }    
	  .card{
		  margin-top: 30px;
		  border-top: 1px solid #eee;
		  padding: 10px 0;
	   }
	   
	}
</style>

在上面代码中实现了:

  1. 在JS部分定义了商品集合,里边包含商品的id,名称,价格,是否选中;
  2. 定义选中事件itemChange,在绑定的方法中获取选中的值,并实时监听子项的选中和取消选中,获得商品的选中状态;
  3. 定义了一个名为 totalPrice 的计算属性(使用 Vue 的 computed 函数),实时计算所有被选中商品(checkedtrue)的总价格。

下面重点说下第3点:使用computed 实时计算选中商品的价格:

javascript 复制代码
const totalPrice = computed(()=>{
	 return goods.value.filter(item=>item.checked).reduce((prev,curr)=>prev+curr.price,0)
})
  1. .filter(item => item.checked)

    • 过滤 goods.value 数组,只保留 checkedtrue 的商品(即用户选中的商品)。
  2. .reduce((prev, curr) => prev + curr.price, 0)

    • 对过滤后的选中商品数组进行归约操作:

      • 从初始值 0 开始,遍历每个商品(curr)。

      • 将当前商品的价格(curr.price)累加到总和(prev)中。

    • 最终返回所有选中商品价格的总和。

相关推荐
摇滚侠20 分钟前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 2
java·spring boot·笔记
MartinYeung542 分钟前
[论文学习]大语言模型越狱的机械可解释性:基于内部归因图的分析
人工智能·学习·语言模型
XiHongShi20161 小时前
51基础学习视频分享(2),三极管,点亮LED灯
单片机·学习
_Narcissus_2 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治
边境悍匪2 小时前
springboot常用注解
java·spring boot·学习
Capricorn19882 小时前
科研引用无法溯源怎么排查?知芽 Notebook Skill 技术机制拆解
大数据·论文阅读·人工智能·笔记·论文笔记
Capricorn19882 小时前
Agent 记忆层接入后引用仍不可信?知芽 Notebook Skill 排障指南
大数据·论文阅读·人工智能·笔记·架构
自小吃多3 小时前
PCB Editor放置元器件笔记
笔记·嵌入式硬件
lhldsg3 小时前
家校托管互通系统开发实战:从需求分析到部署全指南
小程序·uni-app·需求分析
Hotchip_MEMS5 小时前
消费电子声学升级核心器件:MP381A-AB17D MEMS麦克风参数详解与应用场景
人工智能·笔记·物联网·电脑·制造