<template>
<div class="app">
<header>购物车</header>
<section v-show="shopList.length>0">
<dl v-for="(v,i) in shopList" :key="i">
<dt><input type="checkbox" @click="checksFun(v)"
v-model="v.isCheck"><img v-bind:src="v.url"></dt>
<dd>
<p>{{v.name}}</p>
<p>价格:{{v.price | toMoney("aaa")}}
<font>小计:{{v.price*v.num | toMoney}}</font></p>
<p>
<button :disabled="v.num<=1"
@click="v.num=v.num<=1?1: --v.num">-</button>
<span>{{v.num}}</span>
<button @click="v.num++">+</button>
<button @click="delFun(i)">删除</button>
</p>
</dd>
</dl>
</section>
<p class="cart" v-show="shopList.length==0">购物车空空如也~~~~</p>
<div class="box">
<label><input type="checkbox" v-model="checkAll"
@click="checkAllFun">全选</label>
总金额:{{totalMoney() | toMoney}}
<button>去结算({{totalNum()}})</button>
</div>
</div>
</template>
data(){
return{
checkAll:false,
shopList:[{
id:0,
name:"商品1",
url:"img/2_03.jpg",
price:100,
num:7,
isCheck:false
},{
id:1,
name:"商品2",
url:"img/2_06.jpg",
price:60,
num:2,
isCheck:false
},{
id:2,
name:"商品3",
url:"img/2_08.jpg",
price:200,
num:5,
isCheck:false
},{
id:3,
name:"商品4",
url:"img/2_10.jpg",
price:10,
num:6,
isCheck:false
}]
}
},
methods:{
totalMoney(){//总金额
let sum=0;
this.shopList.forEach(element=>{
if(element.isCheck){
sum+=element.price*element.num
}
})
return sum
},
totalNum(){//总小计
let sum=0;
this.shopList.forEach(element=>{
if(element.isCheck){
sum+=element.num
}
})
return sum
},
checkAllFun(){//全选
this.checkAll=!this.checkAll
this.shopList.forEach(element=>{
element.isCheck=this.checkAll
})
},
checksFun(val){//单选
val.isCheck=!val.isCheck;
this.checkAll=this.shopList.every(v=>{return v.isCheck==true})
},
delFun(index){//删除
this.shopList.splice(index, 1);
this.checkAll=this.shopList.every(v=>{return v.isCheck==true})
if(this.shopList.length==0){
this.checkAll=false
}
}
filters:{
toMoney(val){
return "¥"+val.toFixed(2)
}
}
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
Vue.filter("toMoney", function(val) { return "¥" + val.toFixed(2) })
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')