Vue实现购物车列表
最终效果图:
当勾选行时,自动进行总和计算;可以进行单列删除,也可以使用复选框,进行多选批量删除;可以对商品数量进行更改,但商品数量为1时将不能进行减少。
表格html:
引入jquery.js、bootstrap.css进行表格美化,并且引入要用到的vue.js。
<script type="text/javascript" src="../lib/jquery-2.1.0.min.js"></script>
<link rel="stylesheet" href="../lib/bootstrap.css">
<script type="text/javascript" src="../lib/vue.js"></script>
<div class="container">
<div id="list">
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-body">
<template v-if="list.length">
<table class="table table-bordered table-hover table-striped" style="text-align:center;">
<thead style="background-color: #7A8B8B">
<tr>
<td><input id="allcheck" type="checkbox" @click="allcheck(event)" :checked="list.length===listIds.length && listIds.length"></td>
<td>商品名称</td>
<td>商品价格</td>
<td>购买数量</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in list" :key = "index">
<td><input type="checkbox" name="boxs" :value="index" @click="checkedOne(item.id)" :checked="listIds.indexOf(item.id)>=0"></td>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td><button type="button" class="btn btn-xs" @click="del(index)" :disabled="item.count===1">-</button>
{{ item.count }}
<button type="button" class="btn btn-xs" @click="add(index)">+</button></td>
<td><button type="button" class="btn btn-xs" @click="move(index)">删除</button></td>
</tr>
</tbody>
</table>
</template>
<div v-else>购物车为空!</div>
</div>
<div class="panel-footer">共{{ total }}元!
<button type="button" class="btn btn-default" style="float:right;" :disabled="listIds.length==0" @click="deleteAll">批量删除</button>
</div>
</div>
</div>
</div>
</div>
Vue:
①表格数据 :使用v-for进行表格数据绑定
var vm = new Vue({
el:"#list",
data:{
isCheckedAll: false,
listIds: [],
list:[
{
id:1,
name:"aaaaaaa",
price:2222,
count:1
},{
id:2,
name:"bbbbbb",
price:2222,
count:2
},{
id:3,
name:"cccccc",
price:2222,
count:1
}]
},
②计算属性 :判断复选框的勾选情况实时计算总额
computed:{
total:function(){
var total=0;
for(var i = 0 ;i < this.listIds.length ; i++ ){
var n=this.listIds[i];
var item = this.list.find((element) => (element.id == n));
total+=item.count*item.price;
}
return total.toString().replace(/B(?=(\d{3})+$)/g,",");
}
},
③methods:各个按钮的点击事件(包含复选框勾选,全选,数量更改,单行删除,批量删除)
methods:{
checkedOne (listId) {
let idIndex = this.listIds.indexOf(listId);
if (idIndex >= 0) { //如果listIds中已经包含就去除
this.listIds.splice(idIndex, 1);
} else { //如果listIds中没有包含就添加
this.listIds.push(listId);
}
},
del:function(index){
if(this.list[index].count===1) return;
this.list[index].count--;
},
add:function(index){
this.list[index].count++;
},
move:function(index){
this.listIds = [];
this.list.splice(index,1);
},
allcheck:function(e){
this.isCheckedAll = e.target.checked;
if (this.isCheckedAll) {//全选时
this.listIds = [];
this.list.forEach(item => {
this.listIds.push(item.id);
})
} else {
this.listIds = [];
}
},
deleteAll:function(){
this.list = this.list.filter(item => this.listIds.indexOf(item.id) === -1);
this.listIds = [];
}
}
谢谢!!