39,083
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>购物车实例</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css" /> -->
<!-- <script type="text/javascript" src="js/vue.js" ></script> -->
</head>
<body>
<div id="app" v-cloak>
<div v-if="list.length">
<table>
<template v-for="(item,index) in list" :key="item">
<thead>
<tr>
<th>
<input type="checkbox">
{{ item.titleName }}
</th>
<th>序号</th>
<th>商品名称</th>
<th>商品单价</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(p, vi) in item.productList" :key="vi" v-show="p.count>0">
<!--这里的下标为vi,后面几个事件可能也用这个-->
<td><input type="checkbox"></td>
<td>{{ vi+1 }}</td>
<td>{{ p.name }}</td>
<td>{{ p.price }}</td>
<td>
<button @click="handleReduce(index, vi)" :disabled="p.count===1">-</button> {{p.count}}
<button @click="handleAdd(index, vi)">+</button>
</td>
<td>
<button @click="handleRemove(index, vi)">移除</button>
</td>
</tr>
</tbody>
</template>
</table>
<div>总价: ¥ {{totalPrice}}</div>
</div>
<div v-else>购物车为空</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<!-- <script src="index.js"></script> -->
</body>
</html>
<script>
var app = new Vue({
el: '#app',
data: {
list: [{
titleName: '电子产品',
productList: [{
id: 1,
name: 'iPhone 7',
price: 6188,
count: 1,
status: 1
},
{
id: 2,
name: 'iPad Pro',
price: 5188,
count: 1,
status: 1
},
{
id: 3,
name: 'MacBook Pro',
price: 21488,
count: 1,
status: 1
}
]
},
{
titleName: '生活用品',
productList: [{
id: 1,
name: '尺子',
price: 2.00,
count: 1,
status: 1
},
{
id: 2,
name: '包装箱',
price: 29.99,
count: 1,
status: 1
},
{
id: 3,
name: '毛巾',
price: 15.98,
count: 1,
status: 1
}
]
},
{
titleName: '水果蔬菜',
productList: [{
id: 1,
name: '国产香蕉',
price: 2.88,
count: 1,
status: 1
},
{
id: 2,
name: '苹果',
price: 5.11,
count: 1,
status: 1
},
{
id: 3,
name: '车厘子',
price: 29.98,
count: 1,
status: 1
}
]
}
],
/* check_goods: [] */
},
computed: {
totalPrice: function () {
var total = 0;
this.list.forEach(item => {
item.productList.forEach(o => {
if (o.count > 0) {
total += o.price * o.count;
}
});
})
// return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
return total.toLocaleString()
}
},
methods: {
handleReduce: function (index, vi) {
if (this.list[index].productList[vi].count === 1) return;
this.list[index].productList[vi].count--;
},
handleAdd: function (index, vi) {
this.list[index].productList[vi].count++;
},
handleRemove: function (index, vi) {
this.list[index].productList[vi].count = 0;
}
}
});
</script>