效果显示:

购物车效果图

功能代码:

  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

Logo

前往低代码交流专区

更多推荐