console
const app = new Vue({
el: '#app',
data: {
books: [
{id: 1, bookName: '算法导论', publicationDate: '2006-9', price: 85, count: 1},
{id: 2, bookName: 'Unix编程艺术', publicationDate: '2006-2', price: 55, count: 1},
{id: 3, bookName: '代码大全', publicationDate: '2008-10', price: 39, count: 1},
{id: 4, bookName: '编程导论', publicationDate: '2006-3', price: 128, count: 1},
],
checks: []
},
methods: {
delBook(index) {
this.books.splice(index, 1)
const itemIndex = this.checks.indexOf(index)
if (itemIndex !== -1) {
this.checks.splice(itemIndex, 1)
}
},
countIncrement(index) {
this.books[index].count++
},
countDecrement(index) {
this.books[index].count--
},
selectAll() {
if (this.checks.length !== this.books.length) {
this.checks = this.books.map((v,i) => i)
} else {
this.checks = []
}
}
},
computed: {
getTotalPrice() {
return this.checks.reduce((sum, v) => {
return sum + this.books[v].price * this.books[v].count
}, 0)
}
},
filters: {
priceFormat(price) {
return '¥' + price.toFixed(2)
},
bookNameFormat(bookName) {
return "《" + bookName + "》"
}
}
})
<div class="box" id="app">
<div class="panel panel-default" v-if="books.length">
<table class="table">
<thead>
<tr>
<td><input type="checkbox" @click="selectAll" :checked="checks.length === books.length"></td>
<td>#</td>
<td>书籍名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books" :key="item.id">
<td><input type="checkbox" v-model="checks" :value="index"></td>
<td>{{index + 1}}</td>
<td>{{item.bookName | bookNameFormat}}</td>
<td>{{item.publicationDate}}</td>
<td>{{item.price | priceFormat}}</td>
<td>
<button class="btn btn-primary btn-xs" @click="countDecrement(index)" :disabled="item.count <= 1">-</button>
{{item.count}}
<button class="btn btn-primary btn-xs" @click="countIncrement(index)">+</button>
</td>
<td>
<button class="btn btn-danger" @click="delBook(index)">移出</button>
</td>
</tr>
</tbody>
</table>
<h3>总价: {{getTotalPrice | priceFormat}}</h3>
</div>
<div v-else>
<h1>购物车内无物品</h1>
</div>
</div>
.box {
width: 1000px;
margin: 0 auto;
}
.box .table button[disabled=disabled] {
cursor: not-allowed;
}