<template>
<div>
<table>
<tr>
<th><input type="checkbox" v-model="selectAll" />全选/全不选</th>
<th v-for="(item, index) in titles" :key="index">{{ item }}</th>
</tr>
<tr v-for="(item, index) in books" :key="item.name">
<td><input type="checkbox" v-model="item.select" /></td>
<td>{{ index }}</td>
<td>{{ item.name }}</td>
<td>{{ item.date }}</td>
<td>¥{{ item.price.toFixed(2) }}</td>
<td>
<button @click="redu(index)">-</button>
{{ item.num }}
<button @click="add(index)">+</button>
</td>
<td><button @click="del(index)">移除</button></td>
</tr>
<tr>
<td colspan="7" style="text-align: left">总价格为:{{ total }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
titles: ["编号", "书籍名称", "出版日期", "价格", "数量", "操作"],
books: [
{
name: "算法导论",
date: "2006-9",
price: 85,
num: 1,
select: true,
},
{
name: "UNIX编程艺术",
date: "2006-2",
price: 59,
num: 1,
select: true,
},
{
name: "Vue程序设计",
date: "2008-10",
price: 35,
num: 1,
select: true,
},
{
name: "颈椎康复",
date: "2006-3",
price: 129,
num: 1,
select: true,
},
],
};
},
computed: {
total() {
let ret = this.books.reduce((pre, cur) => {
return cur.price * cur.num + pre;
}, 0);
return "¥" + ret.toFixed(2);
},
selectAll: {
get() {
for (let i = 0; i < this.books.length; i++) {
if (!this.books[i].select) {
return false;
}
}
return true;
},
set(newVal) {
this.books.forEach((item, index) => {
// item.select = newVal;
this.$set(this.books, index, newVal);
});
},
},
},
methods: {
add(i) {
if (!this.books[i].select) {
alert("你还没做出选择");
return;
}
this.books[i].num++;
},
redu(i) {
if (!this.books[i].select) {
alert("你还没做出选择");
return;
}
this.books[i].num > 1 ? this.books[i].num-- : "";
},
del(i) {
if (!this.books[i].select) {
alert("你还没做出选择");
return;
}
this.books.splice(i, 1);
},
},
};
</script>
<style lang = "less" scoped>
table {
border-collapse: collapse;
margin: 100px auto;
}
table,
td,
th {
border: 1px solid #000;
}
td,
th {
padding: 10px;
}
</style>