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方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM