vue之路 购物车实例
<template>
<div >
<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>总价(四舍五入):¥{{totalPriceRound}}</div>
<div>总价(不四舍五入):¥{{totalPriceNoRound}}</div>
<div>总价(不处理小数):¥{{totalPrice}}</div>
</template>
<div v-else>购物车为空</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
list:[
{
id:1,
name:'iPhone 7',
price:6188.99,
count:1
},
{
id:2,
name:'iPhone X',
price:9188.66,
count:1
},
{
id:3,
name:'iPad Pro',
price:5188.23,
count:1
},
],
}
},
computed:{
totalPriceRound:function(){ //四舍五入
let total=0;
for(let i=0;i<this.list.length;i++){
let item=this.list[i];
total+=item.price*item.count;
}
total=total.toFixed(2).toString().split(".");
total[0]=total[0].replace(/\B(?=(\d{3})+$)/g,',');
return total.join('.');
},
totalPriceNoRound:function(){ //不四舍五入
let total=0;
for(let i=0;i<this.list.length;i++){
let item=this.list[i];
total+=item.price*item.count;
}
total=parseFloat(total.toString().replace(/(\.\d{2})\d+$/,"$1")).toFixed(2).toString().split(".");
total[0]=total[0].replace(/\B(?=(\d{3})+$)/g,',');
return total.join('.');
},
totalPrice:function(){ //不处理小数
let total=0;
for(let i=0;i<this.list.length;i++){
let item=this.list[i];
total+=item.price*item.count;
}
total=total.toString().split(".");
total[0]=total[0].replace(/\B(?=(\d{3})+$)/g,',');
return total.join('.');
}
},
methods:{
handleReduce(index){
if(this.list[index].count===1) return;
this.list[index].count--;
},
handleAdd(index){
this.list[index].count++;
},
handleRemove(index){
this.list.splice(index,1);
},
},
}
</script>
金额 使用正则千位分隔符,保留两位小数:四舍五入或不四舍五入,或不处理小数

浙公网安备 33010602011771号