<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>简易购物车实现</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<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>
<template v-for="(item,index) in list">
<tr>
<td colspan="5">{{item.categoryName}} ——类别总价:{{categoryToalPrice(index)}}</td>
</tr>
<template v-if="item.data.length">
<tr v-for="(subItem,subIndex) in item.data">
<td>
<input type="checkbox" :checked="item.checked" @click="handleCheck(index,subIndex)">
</td>
<td>{{ subItem.name }}</td>
<td>{{ subItem.price }}</td>
<td>{{ subItem.count }}</td>
<td>
<button type="button" @click="handleReduce(index,subIndex)" :disabled="item.count === 1">-</button>
1
<button type="button" @click="handleAdd(index,subIndex)">+</button>
<button type="button" @click="handleRemove(index,subIndex)">删除</button>
</td>
</tr>
</template>
<template v-else>
<tr>
<td colspan="5">该类别无数据</td>
</tr>
</template>
</template>
</table>
<div>总价:{{ totalPrice }}</div>
</template>
<div v-else>购物车为空</div>
</div>
<script src="js/vue.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/VueShoppingCart.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
VueShoppingCart.js(待优化)
var app = new Vue({
el: "#app",
data: {
list: [{
categoryName: "电子产品",
data: [{
name: "ipad Pro",
price: 9999,
count: 5,
checked: false
},
{
name: "Iphone x",
price: 8888,
count: 3,
checked: false
},
{
name: "MacBook Pro",
price: 1299,
count: 1,
checked: false
}]
}, {
categoryName: "服装",
data: [{
name: "包包",
price: 123,
count: 5,
checked: false
},
{
name: "Nike",
price: 1555,
count: 3,
checked: false
},
{
name: "回力",
price: 120,
count: 1,
checked: false
}]
}]
},
methods: {
handleReduce(index,subIndex) {
if (this.list[index].data[subIndex].count === 1) return;
this.list[index].data[subIndex].count--;
},
handleAdd(index) {
this.list[index].data[subIndex].count++;
},
handleRemove(index,subIndex) {
this.list[index].data.splice(subIndex,1);
},
handleCheck(index,subIndex) {
if (this.list[index].data[subIndex].checked) {
this.list[index].data[subIndex].checked = false;
} else {
this.list[index].data[subIndex].checked = true;
}
}
},
computed: {
totalPrice() {
let total = 0;
for (let i = 0; i < this.list.length; i++) {
var item = this.list[i];
for(let j = 0; j < item.data.length;j++){
let subItem = item.data[j];
if (subItem.checked) {
total += subItem.price * subItem.count;
}
}
}
return total;
},
categoryToalPrice(){
return function(subIndex){
let categoryTotal = 0;
for(let j = 0; j < this.list[subIndex].data.length;j++){
let categoryItem = this.list[subIndex].data[j];
if (categoryItem.checked) {
categoryTotal += categoryItem.price * categoryItem.count;
}
}
return categoryTotal;
}
}
}
});