<template>
<h1>购物车</h1>
<div>
<div v-for="i of arr" :key="i.id" style="margin-bottom: 10px">
<el-button type="info">{{i.name}}</el-button>
<el-button type="primary" @click="subtract(i.id)">-</el-button>
<el-button>{{i.quantity}}</el-button>
<el-button type="primary" @click="add(i.id)">+</el-button>
<el-button>{{i.price}}</el-button>
</div>
<el-button type="info">{{PriceCalculation.quantity}}个</el-button>
<el-button type="info">{{PriceCalculation.price}}</el-button>
<el-button type="primary" @click="settle">结算金额</el-button>
</div>
</template>
<script setup lang="ts">
let arr=reactive([
{id:1,name:'路飞',quantity:1,price:100},
{id:2,name:'索隆',quantity:1,price:200},
{id:3,name:'山治',quantity:1,price:300},
{id:4,name:'乔巴',quantity:1,price:400},
])
const PriceCalculation=computed(()=>{
let assemble={
quantity:0,
price:0
}
arr.forEach(i=>{
assemble.quantity+=i.quantity
assemble.price+= i.quantity * i.price
})
return assemble
})
const subtract=(val:number)=>{
arr.forEach(i=>{
if(i.id==val){
if(i.quantity==1) return
i.quantity--
}
})
}
const add=(val:number)=>{
arr.forEach(i=>{
if(i.id==val){
i.quantity++
}
})
}
const settle=()=>{
const {quantity,price}=PriceCalculation.value
console.log(quantity,price)
}
</script>
<style scoped>
</style>
nuxt3计算属性:购物车
最新推荐文章于 2024-04-26 16:47:03 发布