Vue实现购物车结算功能

效果显示:

购物车效果图

功能代码:

  index.js:

var app = new Vue({
el:'#app',
data:{
list:[
{
id:1,
name:'redmi k20',
price:2000,
count:1
},
{
id:2,
name:'meizu 16xs',
price:1499,
count:1
},
{
id:3,
name:'realme X',
price:1499,
count:1
}
]

},
computed:{
totalPrice: function () {
var total =0;
for(var i = 0;i<this.list.length;i++){
var item = this.list[i];
total +=item.price*item.count;
}
return total.toString().replace(/\B(?=(\d{3})+$)/g,',');
}
},
methods:{
handleReduce:function (index) {
if(this.list[index].count ===1)return;
this.list[index].count--;
},
handleAdd:function (index) {
this.list[index].count++;
},
handleRemove:function (index) {
this.list.splice(index,1);
}
}
});

index.html:

<div id="app" v-cloak>
<template v-if="list.length">
<table>
<thead>
<tr>
<th></th>
<th>商品名称</th>
<th>商品单价</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for = "(item,index) in list">
<td>{{ index + 1}}</td>
<td>{{ item.name}}</td>
<td>{{ item.price}}</td>
<td>
<button
@click="handleReduce(index)"
:disabled="item.count ===1"
>-</button>
{{item.count}}
<button @click="handleAdd(index)">+</button>
</td>
<td>
<button @click="handleRemove(index)">移除</button>
</td>

</tr>
</tbody>
</table>
<div>总价:¥{{totalPrice}}</div>
</template>
<div v-else>购物车为空</div>
</div>

!:
1.computed:计算属性
2.JavaScript splice方法

转载于:https://www.cnblogs.com/yhliu/p/11237739.html

Vue3中,购物车结算并添加订单的方法可以通过以下步骤完成: 1. 在Vue组件中,创建一个名为"cart"的对象,用于存储购物车相关的据,如商品列表、总价等信息。 ```javascript data() { return { cart: { items: [], // 商品列表 total: 0 // 总价 } } } ``` 2. 在购物车页面中,用户可以选择要购买的商品或者移除已选择的商品,这些操作可以通过添加方法和移除方法来实现。 ```javascript methods: { addItem(item) { this.cart.items.push(item); // 将商品添加到购物车中 this.cart.total += item.price; // 更新购物车总价 }, removeItem(item) { const index = this.cart.items.indexOf(item); if (index > -1) { this.cart.items.splice(index, 1); // 从购物车中移除商品 this.cart.total -= item.price; // 更新购物车总价 } } } ``` 3. 当用户点击结算按钮时,可以调用结算方法来生成订单并跳转到订单页面。 ```javascript methods: { settle() { const order = { items: this.cart.items, // 将购物车中的商品列表赋值给订单 total: this.cart.total // 将购物车中的总价赋值给订单 } // 发送订单据到后台进行处理,并等待返回结果 // 处理成功后,可以跳转到订单页面,并清空购物车中的商品列表和总价 } } ``` 通过以上步骤,我们可以实现Vue3中购物车结算添加订单的方法。当用户选择要购买的商品并点击结算按钮时,会生成一个订单并将该订单发送到后台进行处理。处理成功后,可以跳转到订单页面,并清空购物车中的商品列表和总价。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值