vue简单的购物车功能
- 目标:实现全选 当book的sel有变化时候都需要检测是否为全选
- 目标:实现全选与反选
- 目标:计算总价,总数量
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./vue/vue.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
input {
width: 25px;
}
</style>
</head>
<body>
<div id="app">
<table border="" cellspacing="" cellpadding="">
<tr>
<th><input type="checkbox" @change="changeAll()" v-model="all"></th>
<th>id</th>
<th>名称</th>
<th>日期</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
<tr v-for="item in books" :key="item.id">
<td><input type="checkbox" v-model="item.sel"></td>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>${{item.price}}</td>
<td>
<button @click="cel(item,-1)" :disabled="item.num <=1">-</button>
<input type="text" v-model="item.num" @input="check(item)">
<button @click="cel(item,+1)" :disabled="item.num >=10">+</button>
</td>
<td><button @click="del(item)">删除</button></td>
</tr>
</table>
<p>总价格:${{total.price}} 总数量:{{total.num}}</p>
</div>
</body>
<script type="text/javascript">
new Vue({
el : "#app",
data : {
all : true,
books : [
{sel : true,id : 1,name : "小红书",price : 23,num : 1,date : "2019-30"},
{sel : true,id : 2,name : "小4书",price : 22,num : 1,date : "2019-30"},
{sel : true,id : 3,name : "小2书",price : 55,num : 1,date : "2019-30"},
{sel : true,id : 4,name : "小0书",price : 33,num : 1,date : "2019-30"},
{sel : true,id : 5,name : "小8书",price : 89,num : 1,date : "2019-30"}
]
},
watch : {
books : {
handler : function() {
this.all = this.books.every(item => item.sel);
},
deep : true
}
},
methods : {
changeAll() {
this.books.forEach(item => item.sel = this.all);
},
cel(item,n) {
item.num += n;
this.check(item);
},
check(item) {
if(item.num <= 1) {
item.num = 1;
}
if(item.num > 10) {
item.num = 10;
}
},
del(item) {
var flag = window.confirm("确定删除吗?");
if(flag) {
var ind = this.books.indexOf(item);
this.books.splice(ind,1);
}
}
},
computed : {
total : function() {
var price = 0;
var num = 0;
this.books.forEach( item => {
if(item.sel) {
price += item.num * item.price;
num += item.num *1;
}
})
return ({price,num});
}
}
})
</script>
</html>