运行截图:
 html:
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<td v-for="item in thead">{{item}}</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="sub(index)" v-bind:disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="add(index)">+</button>
</td>
<td>
<button @click="removeHandle(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<span>共计:{{totalPrice | showPrice}}</span>
</div>
<h2 v-else>购物车为空!</h2>
</div>
CSS:
<style>
table {
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
border: 1px solid #cbcbcb;
}
td,th {
border-left: 1px solid #cbcbcb;
font-size: inherit;
margin: 0;
overflow: visible;
padding: .5em 1em;
}
tr {
border: 1px solid #000000;
}
thead {
background-color: #e0e0e0;
color: #000;
text-align: left;
vertical-align: bottom;
}
</style>
vue:
const app = new Vue({
el: '#app',
data: {
thead: ['', '书籍名称', '出版日期', '价格', '购买数量', '操作'],
books:[
{id: 1, name: '《算法导论》', date: '2006-9', price: 85.00, count: 1},
{id: 2, name: '《UNIX编程艺术》', date: '2006-2', price: 59.00, count: 1},
{id: 3, name: '《编程珠玑》', date: '2008-10', price: 39.00, count: 1},
{id: 4, name: '《代码大全》', date: '2006-3', price: 128.00, count: 1},
],
flag: false
},
methods: {
sub(index) {
this.books[index].count--
},
add(index) {
this.books[index].count++
},
removeHandle(index) {
this.books.splice(index, 1)
}
},
computed:{
totalPrice: function () {
let total = this.books.reduce((prev, cur) => {
return prev += cur.count * cur.price
}, 0.00)
return total
}
},
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
}
})
|