效果图
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<!--v-if为true时显示 为false是不显示 -->
<div v-if="list.length">
<table>
<thead>
<tr>
<th><input id="quan" type="checkbox" v-model="isAll" />全选</th>
<th>序号</th>
<th>名称</th>
<th>单价</th>
<th>数量</th>
<th>总价</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in list" :key="item.id">
<td><input type="checkbox" class="checkItem" v-model="chechData" :value="item.id" /></td>
<td >{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="jianClick(index)" v-bind:disabled="item.num <= 1">-</button>
{{item.num}}
<button @click="jiaClick(index)">+</button>
</td>
<td>{{item.jiaq}}</td>
</tr>
</tbody>
</table>
<div><p>总价{{total}}</p></div>
</div>
<!-- 在不执行v-if 的情况下执行v-else -->
<h2 v-else>购物车为空</h2>
</div>
<script src="../js/vue.min.js"></script>
<script>
const app = new Vue({
el:'#app',//挂载
data: {
list: [
{ id: 1, name: "Apple", price: 10, num: 1 ,jiaq:10},
{ id: 2, name: "Banana", price: 20, num: 1 ,jiaq:20},
{ id: 3, name: "Orange", price: 30, num: 1 ,jiaq:30}
],
chechData:[]
},
methods:{//定义函数
jianClick(index){
this.list[index].num--;
this.list[index].jiaq=this.list [index].num * this.list[index].price
},
jiaClick(index){
this.list[index].num++;
this.list[index].jiaq=this.list [index].num * this.list[index].price
},
removeClick(index){
this.list.splice(index,1);
}
},
computed:{//计算属性
isAll:{
get(){
//单选变多选.随着选中的等于是数据库中的长度表达式true 全选被选中
return this.list.length === this.chechData.length;
},
set(bol){
if(bol){
//将item.id写入checkData
this.chechData = this.list.map(item => item.id);
}else{
this.chechData = [];
}
}
},
total(){
// 1. 过滤出list中被选中了的商品
// let arr = this.list.filter(item => {return this.chechData.indexof(item.id) > -1
// })
let arr = this.list.filter(item => {
return this.chechData.indexOf(item.id) > -1
})
//2. 将arr中每个商品的总价加起来
let ta=0;
ta =arr.reduce((jiaq,item )=>{
return ta += item.jiaq
},0)
return ta
}
},
filters:{//定义过滤属性
showPrice(price){
return "¥" + price.toFixed(2);
}
},
// watch:{
// chechData:{
// handler(){
// if(this.chechData.length == 3){
// document.querySelector("#quan").checked =true;
// }else{
// document.querySelector("#quan").checked =false;
// }
// }
// },
// deep:true //深度监听
// }
})
</script>
</body>
</html>