直接上代码
注释是精华:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
table {
border-collapse: collapse;
/* table-layout: fixed; */
width: 100%;
}
td, th {
border: 1px solid #999;
}
th {
/* width: 16%; */
}
</style>
</head>
<body>
<div id="root">
<table>
<thead>
<tr>
<th><input type="checkbox" v-model="isAllChecked">全选</th>
<th>名称</th>
<th>单价</th>
<th>数量</th>
<th>总价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- 遍历cart -->
<tr v-for="item of cart" :key="item.id">
<td>
<input
type="checkbox"
v-model="checkedCartItems"
:value="item.id"
>
</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.count}}</td>
<!-- 这里本来应该到子组件里去做的,现在还没学 -->
<td>{{item.count * item.price}}</td>
<!-- 点击按钮触发删除事件(通过id进行删除) -->
<td><button @click="handleItemDelete(item.id)">删除</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="6">总共有{{totalCount}}件商品,合计总价{{totalPrice}},选中的合计总价{{checkedTotalPrice}}</td>
</tr>
</tfoot>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
const vm = new Vue({
el: '#root',
data: {
checkedCartItems: [],//被勾选的数据
cart: [{
id: 1,
name: 'apple',
price: 5000,
count: 8
}, {
id: 2,
name: 'huawei',
price: 3123,
count: 11
}, {
id: 3,
name: 'xiaomi',
price: 2000,
count: 20
}, {
id: 4,
name: 'meizu',
price: 6123,
count: 18
}]
},
computed: {
// 计算总数量
totalCount() {
return this.cart.reduce((total, item) => {
total += item.count;
return total
}, 0);
},
// 计算总价
totalPrice() {
return this.cart.reduce((total, item) => {
total += item.count * item.price;
return total
}, 0);//赋初值为0
},
checkedTotalPrice() {
//筛选出被选择的商品
const checkedItems = this.cart.filter(item => {
return this.checkedCartItems.some(id => item.id === id);
// return this.checkedCartItems.includes(item.id);
});
//计算被勾选商品的总价格
return checkedItems.reduce((total, item) => {
total += item.count * item.price;
return total
}, 0);
},
// 是否全选
isAllChecked: {
// 在调用时(全选时)自动执行
get() {//返回的购物车数据条数与勾选条数相同
return this.cart.length === this.checkedCartItems.length;
},
// 在赋值时(勾选时)自动执行
set(v) {
if(v) {
this.checkedCartItems = this.cart.map(item => item.id);
} else {
this.checkedCartItems = [];
}
}
}
},
methods: {
handleItemDelete(id) {
// 筛选掉要删除的id对应的数据,重新赋值给cart
this.cart = this.cart.filter(item => item.id !== id);
// 如果不改下面的值,全选不对!!!
// 为避免影响全选,必须将删除掉的元素筛选掉,再进行勾选
this.checkedCartItems = this.checkedCartItems.filter(itemId => itemId !== id);
}
}
})
</script>
</body>
</html>