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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)