<template>
<div>
<table>
<tr>
<th><input type="checkbox" v-model="isCheckAll">全选/全不选</th>
<th v-for="item in titles" :key="item">{{item}}</th>
</tr>
<tr v-for="item,index in books" :key="index">
<td><input type="checkbox" v-model="checkList[index]"></td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{ '¥'+item.price.toFixed(2)}}</td>
<td>
<button @click="red(index)">-</button>
{{item.num}}
<button @click="add(index)">+</button>
</td>
<td><button @click="del(index)">移除</button></td>
</tr>
<tr>
<td colspan="6" style="text-align: right;">总价:{{total}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data () {
return {
// checkList保存每一项的勾选情况
checkList:[],
// isCheckAll:true,
titles: ['书籍名称', '出版日期', '价格', '数量', '操作'],
books: [
{
name: '算法导论',
date: '2006-9',
price: 85,
num: 1
},
{
name: 'UNIX编程艺术',
date: '2006-2',
price: 59,
num: 1
},
{
name: 'Vue程序设计',
date: '2008-10',
price: 35,
num: 1
},
{
name: '颈椎康复',
date: '2006-3',
price: 129,
num: 1
},
]
}
},
created(){
// 根据books有多少项,决定checkList
this.checkList = this.books.map(()=>false);
},
computed:{
// isCheckAll来表示 全选按钮是否被勾上
isCheckAll:{
get(){
// 特点: 返回true就勾上,false就没有勾上
// 看isCheckAll 和 checkList的关系
// checkList只要有一个为false ( 包含false ), isCheckAll就要返回false
return !this.checkList.includes(false)
},
set(newVal){
// 用户点击全选按钮,会触发这个方法的执行
console.log(newVal);
// 把checkList里面的值都改成新的值newVal
this.checkList = this.checkList.map(()=>newVal);
}
},
total(){
let ret = this.books.reduce((pre,cur,index)=>{
// index 当前这一项的下标/索引
// if(这一项(checkList对应的这一项是不是为true)有没有打勾){
if(this.checkList[index]){
return cur.price*cur.num + pre
}else{
return pre
}
},0)
return '¥ '+ret.toFixed(2)+ " 元"
}
},
methods:{
del(i){
// 删除books的元素的同时, 删除checkList的元素
this.books.splice(i,1);
this.checkList.splice(i,1);
},
add(i){
this.books[i].num++
},
red(i){
if(this.books[i].num>1){
this.books[i].num--
}
}
}
}
</script>
<style lang = "less" scoped>
*{
padding: 0;
margin: 0;
list-style: none;
}
table,td,th{
border: 1px solid #000;
}
table{
border-collapse: collapse;
/* margin: auto; */
}
th,td{
padding: 10px;
}
</style>