<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
[v-cloak] {
display: none;
}
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
}
th,td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th {
background: #f7f7f7;
color: #5c6b77;
font-weight: 600;
white-space: nowrap;
}
</style>
<body>
<div id="app" v-cloak>
<template v-if="list.length">
<table>
<thead>
<tr>
<th>序号</th>
<th>水果名称</th>
<th>水果单价(kg)</th>
<th>购买量(kg)</th>
<th>操作</th>
<th>
<!-- <button @click="selectAll">全选</button> -->
<input type="checkbox" @click="selectAll" :checked="isSelectAll">全选
</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="reduce(index)"
:disabled="item.count === 1">-</button>
{{ item.count }}
<button @click="add(index)">+</button>
</td>
<td>
<button @click="remove(index)">移除</button>
</td>
<td>
<input type="checkbox" @click="select(index)" :checked="item.isSelect">
</td>
</tr>
</tbody>
</table>
<div>总价:¥ {{ totalPrice }}</div>
</template>
<div v-else>购物车为空</div>
</div>
<script src="vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
isSelectAll: false,
list: [
{
id: 1,
name: '苹果',
price: 6,
count: 1,
isSelect: false
},
{
id: 2,
name: '葡萄',
price: 8,
count: 1,
isSelect: false
},
{
id: 3,
name: '橙子',
price: 10,
count: 1,
isSelect: false
}
]
},
computed: {
totalPrice: function(){
var total = 0;
for(goods of this.list){
if(goods.isSelect){
total += goods.price * goods.count;
}
}
return total;
}
},
methods: {
reduce: function(index){
if(this.list[index].count === 1) return;
this.list[index].count--;
},
add: function(index){
this.list[index].count++;
},
remove: function(index){
this.list.splice(index,1);
},
select: function(index){
var _this = this;
var goods = _this.list[index];
goods.isSelect = !goods.isSelect;
var isSelectShopAll = true;
for(shop of _this.list){
if(shop.isSelect === false){
isSelectShopAll = false;
}
}
if(isSelectShopAll){
_this.isSelectAll = true;
}else{
_this.isSelectAll = false;
}
},
selectAll: function(){
this.isSelectAll = !this.isSelectAll;
for(goods of this.list){
goods.isSelect = this.isSelectAll;
}
}
}
})
</script>
</body>
</html>
购物车小案例
于 2023-06-16 15:10:54 首次发布