利用Vue实现一个简单的购物车功能

开始学习Vue的小白,dalao多多指正

想要实现下面这个界面,包含总价计算、数量增加和移除功能

利用Vue实现一个简单的购物车功能

 

 话不多说代码如下

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>小购物车</title> </head> <body> <div> <table> <thead> <td>书籍名称</td> <td>书籍名称</td> <td>出版日期</td> <td>价格</td> <td>购买数量</td> <td>操作</td> </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="decrement(index)" v-bind:disabled="item.count <= 1">-</button> {{item.count}} <button @click="increment(index)">+</button> </td> <td> <button @click="removeBook(index)">移除</button> </td> </tr> </tbody> </table> <font>总价:{{toltalPrice | showPrice}}</font> </div> <script src="http://www.likecs.com/js/vue.js"></script> <script> const hello = new Vue({ el:'#app', data:{ message:'Hello Vue !', books :[ { id:1, name:'编程大法', date:'2020-5', price:999.00, count:1 }, { id:2, name:'编程大法', date:'2020-5', price:999.00, count:1 }, { id:3, name:'编程大法', date:'2020-5', price:999.00, count:1 }, { id:4, name:'编程大法', date:'2020-5', price:999.00, count:1 } ] }, filters: { showPrice(price) { return '¥'+price.toFixed(2); } }, methods:{ decrement(index){ this.books[index].count--; }, increment(index){ this.books[index].count++; }, removeBook(index){ this.books.splice(index,1); } }, computed:{ toltalPrice(){ let toltalPrice=0; for(let i=0;i<this.books.length;i++){ toltalPrice += this.books[i].price * this.books[i].count; } return toltalPrice; } } }) </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsxggp.html