利用bootstrap.min.css 布局和vue.js的简易购物车
computed计算总价,watch监听checked的全选和全不选,选中的单位才会计算到总价
html代码
<script src="./vue.js"></script>
<link rel="stylesheet" href="./bootstrap.min.css">
//引用的插件
<div id="app">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th width="40px" scope="col"><input v-model="ischecked" type="checkbox"></th>
{{ischecked}}
<th width="20%" scope="col">商品名称</th>
<th width="20%" scope="col">价格</th>
<th width="20%" scope="col">数量</th>
<th width="20%" scope="col">总价</th>
<th width="20%" scope="col">操作</th>
</tr>
</thead>
<tbody>
<tr v-for='item,index in list'>
<th scope="row">
<input type="checkbox" @change.stop='checked' v-model='item.ischeck'></th>
<td>{{item.name}}</td>
<td>{{item.money}}</td>
<td>
<button class="btn btn-outline-secondary btn-sm" @click='item.num<=0?item.num=0:item.num-- '>-</button>
<span style="padding: 0 10px;"> {{item.num}} </span>
<button class="btn btn-outline-danger btn-sm" @click='item.num++ '>+</button>
</td>
<td>
¥ {{(item.money*item.num).toFixed(2)}}
</td>
<td>
<a href="javascript:;" @click='del(item.userid) ' class="btn btn-outline-primary btn-sm">删除</a>
</td>
</tr>
<tr>
<td colspan="5" align="right">总价</td>
<td>{{zongjia.toFixed(2)}}</td>
</tr>
</tbody>
</table>
</div>
vue.js
<script>
new Vue({
el: '#app ',
data: {
//按钮是否被选中了
ischecked: false,
//数据
list: [{
name: '华为无线路由器 ',
money: 399.99,
num: 1,
ischeck: true
}, {
name: '小米智能网卡 ',
money: 199.99,
num: 1,
ischeck: false
}, {
name: 'Apple iPad mini ',
money: 3999,
num: 1,
ischeck: false
}, {
name: 'NFC一卡通 ',
money: 100,
num: 1,
ischeck: false
}]
},
methods: {
del(id) {
var index = this.list.findIndex((n) => {
return n.userid == id
});
this.list.splice(index, 1);
},
checked() {
this.list.ischeck = !this.list.ischeck;
}
},
watch: {
ischecked(a, b) {
if (this.ischecked) {
for (let i = 0; i < this.list.length; i++) {
this.list[i].ischeck = true
}
} else {
for (let i = 0; i < this.list.length; i++) {
this.list[i].ischeck = false
}
}
}
},
computed: {
zongjia() {
let sum = 0;
for (let i = 0; i < this.list.length; i++) {
if (this.list[i].ischeck === true) {
sum += this.list[i].money * this.list[i].num
}
}
return sum
}
},
mounted() {
},
})
</script>