效果图:
代码部分:
index.html
<div id="app"> <div v-if="books.length"> <table> <thead> <tr> <th></th> <th>书籍名称</th> <th>出版日期</th> <th>价格</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(item,index) in books"> <td>{{item.id}}</td> <td>{{item.bookName}}</td> <td>{{item.date}}</td> <td>{{item.price | showPrice}}</td> <td> <button @click="decrement(index)" :disabled="item.count<=1">-</button> {{item.count}} <button @click="increment(index)">+</button> </td> <td> <button @click="removeClick(index)">移除</button> </td> </tr> </tbody> </table> <h2>总价格:{{getTotalPrice | showPrice}}</h2> </div> <div v-else> <h2>购物车为空</h2> </div> </div> <script src="../js/vue.js"></script> <link rel="stylesheet" href="style.css"> <script src="main.js"></script>
main.js
const app = new Vue({ el: '#app', data: { books: [ { id: 1, bookName: '《算法导论》', date: '2006-9', price: 85.00, count: 1 }, { id: 2, bookName: '《UNIX编程艺术》', date: '2006-2', price: 59.00, count: 1 }, { id: 3, bookName: '《编程珠玑》', date: '2008-10', price: 39.00, count: 1 }, { id: 4, bookName: '《代码大全》', date: '2006-3', price: 128.00, count: 1 }, ] }, computed: { getTotalPrice() { // let result = 0; // for(let i = 0;i<this.books.length;i++){ // result += this.books[i].count*this.books[i].price // } // return result; return this.books.reduce((a,b)=>a+b.price*b.count,0) } }, methods: { // getFinalPrice(price) { // return '¥'+price.toFixed(2) // } increment(index) { this.books[index].count++; }, decrement(index) { this.books[index].count--; }, removeClick(index) { this.books.splice(index,1) } }, filters: { showPrice(price) { return '¥'+price.toFixed(2) } } })
style.css
#app table { text-align: center; width: 500px; }