<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
input[type="checkbox"]{
width: 18px;
height: 18px;
vertical-align:top;
}
input[type="text"]{
width: 30px;
height: 15px;
}
</style>
<body>
<div id="app">
<h2>购物车</h2>
<hr />
<div class="checkDiv" v-for="(good,index) in goods">
<input type="checkbox" @click="checkOne(good.id)" :checked="goodChecked.indexOf(good.id)>=0"/>
<span class="goodName">{{good.name}}</span>
<button class="minute" @click="minute(index)">-</button>
<input type="text" v-model="good.num" @input="change(index)" >
<button class="add" @click="add(index)">+</button>
<span class="price">{{good.price}}</span>
</div>
<hr />
<input type="checkbox" id="allCheck" @click="checkAll()" :checked="isCheckAll"/>全选
<span>已选数量:{{checkCount}}</span>
<span>总额:{{AllMoney}}</span>
</div>
</body>
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
<script>
var goods=[
{id:1,name:'裙子',num:1,price:130},
{id:2,name:'衬衫',num:1,price:80},
{id:3,name:'鞋子',num:1,price:100},
{id:4,name:'帽子',num:1,price:30}
];
var goodChecked=[1,3,4];
var checkCount=goodChecked.length;
var app=new Vue({
el:'#app',
data:{
// goodCount:0,
AllMoney:0,//总额
checkCount:checkCount,//选中商品数量
goodChecked:goodChecked,//选中商品
isCheckAll:false,//是否全选
goods:goods//所有商品
},
created:function(){
this.allMoney();
},
methods:{
checkAll:function(){
this.isCheckAll=!this.isCheckAll;
if(this.isCheckAll){
this.goodChecked=[];
this.goods.forEach(function(good){
this.goodChecked.push(good.id);
},this)
}else{
this.goodChecked=[];
}
this.checkCount=this.goodChecked.length;
this.allMoney();
},
checkOne:function(id){
var idIndex=this.goodChecked.indexOf(id);//返回id所在的位置
if(idIndex>=0){//包含
this.goodChecked.splice(idIndex,1);
}else{
this.goodChecked.push(id);//不包含则加入数组
}
this.checkCount=this.goodChecked.length;
//判断所有复选框是否全部选中
if(this.checkCount==this.goods.length){//全选中
this.isCheckAll=true;
}else{
this.isCheckAll=false;
}
this.allMoney();
},
allMoney:function(){
console.log("this.AllMoney>>"+this.AllMoney);
var money=0;
this.goods.forEach(function(good){
if(this.goodChecked.indexOf(good.id)>=0){//选中
money=money+good.num*good.price;
}
console.log(this.goodChecked);
},this);
this.AllMoney=money;
},
add:function(id){
this.goods[id].num++;
this.allMoney();
},
minute:function(index){
if(this.goods[index].num>0){
if(this.goods[index].num==1){
if(confirm("是否确定删除改商品?")){
if(this.goodChecked.indexOf(goods[index].id)>=0){
this.goodChecked.splice(this.goodChecked.indexOf(goods[index].id),1);
}
this.goods.splice(index,1);
}
this.checkCount=this.goodChecked.length;
}else{
this.goods[index].num--;
}
}else{
this.goods[id].num=0;
}
this.allMoney();
},
// 输入商品购买数量触发事件
change:function(id){
this.allMoney();
}
}
})
</script>
</html>