uniapp 8.3

本文探讨了在Vue中如何使用watch、computed和reduce计算商品总价,以及如何通过watch监听数据变化。通过实例展示了如何利用forEach、filter和reduce方法处理数组并修改对象状态。
摘要由CSDN通过智能技术生成

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

计算总价   watch   computed  reduce   修改数组对象中的某个值    


提示:以下是本篇文章正文内容,下面案例可供参考

计算总价

1.forEach()

this.list[index].status = !item.status
 this.allPrice = 0
 this.list.forEach((it,idx)=>{
 if(it.status==true){
  this.allPrice = this.allPrice +  it.price * it.num   
}
})

2 filter()

 let sum=0
 this.list.filter((item)=>{sum=sum+item.price*item.num})
 this.allPrice=sum
  return this.allPrice

3 reduce()

computed: {
	getAllPrice() {
return this.list.filter(it => it.status).reduce((acc, it) => acc + it.price * it.num, 0)
			}

computed

computed 计算属性通常适合做一些映射、多对一时进行的操作

<view>{{reverse}}</view>

 str:'123456',

computed:{
					   reverse(){
						 return  this.str.split('').reverse().join('')
					   }//654321

watch

<input type="text" v-model="word">

word='word'

watch:{
word(newVal, oldVal) {
console.log('最新值是:'+newVal,"原来的值是:"+ oldVal);
								}
							},


	      		复杂数据类型这么写监听不到
	      			
	      			list:{
	      				deep:true, // 开启深度监听 专门对付复杂数据类型
	      				immediate:true, // 首次监听 
	      				handler:(newValue, oldValue)=>{
	      					//	console.log('list新值:',newValue, 'list旧值',oldValue);
	      				}
	      			}

  reduce()

array= [1, 2, 3, 4];


 array.reduce(
 (acc,item) =>   acc=acc+item,
 0
);//10



 修改数组对象中的某个值

通过索引

this.list[index].status = true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值