基于Vuejs实现购物车功能

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我的vue购物车</title> <link href="https://www.jb51.net/css/bootstrap.min.css"> <link href="https://www.jb51.net/css/style.css"> <script src="https://www.jb51.net/js/vue.js"></script> <script src="https://www.jb51.net/js/data.js"></script> </head> <body> <div> <template v-if="data.length"> <h3>我的购物车:</h3> <div> <div> <span>商品名称</span> <span>商品单价</span> <span>商品数量</span> <span>操作</span> </div> <div v-for="item in data"> <span>{{item.name}}</span> <span>{{item.price}}</span> <span> <em v-on:click="add($index)" :class="{off:item.count==11}">+</em> {{item.count}} <em v-on:click="reduce($index)" :class="{off:item.count==1}">-</em> </span> <span v-on:click="remove(item)">移除</span> </div> </div> <h2>清单:</h2> <span>商品总价:{{price |currency '$' 2}}</span> </template> <template v-else> <div> <h1>您的购物车空了</h1> <p>是否去重新挑选</p> <p><a href="#" role="button">重新挑选</a></p> </div> </template> </div> </body> <script> new Vue({ el:'.container', data:{ data:data }, computed:{ price:function () { var price = 0; for(var i=0;i<this.data.length;i++){ var self = this.data[i]; price += self.count * self.price; } return price; } }, methods:{ add:function ($index) { var self = this.data[$index]; if(self.count >10){ return false; } self.count++; }, reduce:function($index){ var self = this.data[$index]; if(self.count <= 1){ return false } self.count--; }, remove:function(item){ this.data.$remove(item); } } }) </script> </html>

css:

h3{ text-align: center; } .left{ margin-left: 14%; } .item{ text-align: center; padding: 3%; } .add{ margin-left: 15%; } .off{ background-color: lightgrey; border: 1px solid lightgrey; }

js: 

/** * Created by Administrator on 2016/7/29. */ var data = [ { name:'IPhone 6', price:5466, id:1, count:1 }, { name:'IMac', price:7466, id:2, count:1 }, { name:'iPad', price:5400, id:3, count:1 } ]

本文已被整理到了《Vue.js前端组件学习教程》,欢迎大家学习阅读。

关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。

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

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