vue實現簡單的購物車功能
本文實例為大傢分享瞭vue實現簡單購物車功能的具體代碼,供大傢參考,具體內容如下
1.實現效果:
2.涉及到的知識點:
toFixed函數、過濾器、reduce高階函數、v-bind:disabled、v-if
3.代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>書籍購物車案例</title> <style> table { border: 1px solid #e9e9e9; border-collapse: collapse; border-spacing: 0; } th, td { padding: 8px 16px; border: 1px solid #e9e9e9; text-align: left; } th { background-color: #f7f7f7; color: #5c6b77; font-weight:600; } </style> </head> <body> <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.name}}</td> <td>{{item.date}}</td> <td>¥{{item.price | finalPrice}}</td> <td> <button @click="item.count--" :disabled="item.count <=1">-</button> {{item.count}} <button @click="item.count++">+</button> </td> <td><button @click="btndelete(index)">移除</button></td> </tr> </tbody> </table> <h2>總價格:{{sumPrice | finalPrice}}</h2> </div> <div v-else><h2>購物車為空</h2></div> </div> <script src="../../js/vue.js"></script> <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> --> <script> const app = new Vue({ el: '#app', data: { books: [ { id: 1, name: '《算法導論》', date: '2006-9', price: 85.00, count:1 }, { id: 2, name: '《算法導論》', date: '2006-9', price: 85.00, count:1 }, { id: 3, name: '《算法導論》', date: '2006-9', price: 85.00, count:1 }, { id: 4, name: '《算法導論》', date: '2006-9', price: 85.00, count:1 }, { id: 5, name: '《算法導論》', date: '2006-9', price: 85.00, count:1 } ] }, methods: { btndelete(index){ this.books.splice(index,1); } }, filters: { finalPrice(price){ return '¥' + price.toFixed(2); } }, computed: { sumPrice(){ // 計算價格法1: // let sum = 0; // for(let book of this.books) { // sum += book.price * book.count; // } // return sum; // 計算價格法2,使用reduce函數。 return this.books.reduce(((preValue,book)=>preValue + book.count * book.price),0); } } }) </script> </body> </html>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。