<table width="800" border="1" cellpadding="0" cellspacing="0">
<tr>
<th>编号</th>
<th>图片</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in goods">
<td>{{index+1}}</td>
<td><img :src="item.img"></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="jian(index)">-</button>
<input type="number`-" v-model="item.num">
<button @click="jia(index)">+</button>
</td>
<td>{{item.price*item.num|fixed2}}</td>
<td><button @click="del(index)">删除</button></td>
</tr>
<tr>
<td colspan="7">
订单总数量:{{total.num}}
订单总价格:{{total.price|fixed2}}
</td>
</tr>
</table>
// 定义 保留 两位小数的过滤器
Vue.filter(‘fixed2’,function(value) {
return value.toFixed(2);
});
new Vue({
// 控制绑定容器
el: ‘#container’,
// 绑定的数据
data:{
goods:[
{id:1,name:‘西瓜’,price:10.9,num:2,img:‘images/1.jpg’},
{id:2,name:‘干牛肉’,price:5.85,num:3,img:‘images/2.jpg’},
{id:3,name:‘鸭’,price:4.23,num:1,img:‘images/3.jpg’},
{id:4,name:‘牛肉粒’,price:28.88,num:1,img:‘images/4.jpg’},
{id:5,name:‘酸奶’,price:6.66,num:2,img:‘images/5.jpg’},
{id:6,name:‘黄瓜’,price:2.51,num:2,img:‘images/6.jpg’}
]
},
computed:{
total:function(){
var total = {price:0,num:0}
for(var i=0;i<this.goods.length;i++){
// 总数量
total.num += this.goods[i].num;
// 总价格
total.price += this.goods[i].pricethis.goods[i].num;
}
// 返回订单总数量和总价格
return total;
},
},
methods:{
jian:function(index){
/ 数量 最少为1
this.goods[index].num–;
if(this.goods[index].num<1){
this.goods[index].num = 1;
}
*/
console.log(this.goods[index].num)
if(this.goods[index].num<2){
this.del();
}else{
this.goods[index].num–;
}
},
jia:function(index){
this.goods[index].num++;
},
// 删除
del:function(index){
if(confirm(‘您确定要从购物车里删除此产品吗?’)){
this.goods.splice(index,1);
}
}
}
});