看到网上vue实现购物车一个demo,但是发现问题挺多的,一些浏览器兼容性也不好,还有一些写法过于繁琐,所以改写了该demo重新发布,废话不多说,直接贴代码。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="css/bootstrap.min.css"> <script src="js/vue.min.js"></script> <title></title> </head> <body> <div class="container" id="app"> <h2 class="page-header">购物车</h2> <table class="table"> <tr> <th><label><input type="checkbox" @click="check_all" :checked="check_goods.length == cart_list.length"/>全选</label></th> <th>商品名称</th> <th>商品价格</th> <th>数量</th> <th>操作</th> </tr> <tr v-for="(cart,index) in cart_list" :key="index"> <td><input type="checkbox" :value="cart" v-model="check_goods" /></td> <td>{{cart.goods_name}}</td> <td>{{cart.goods_price}}</td> <td class="col-xs-3"> <input :disabled="cart.num <= 1" type="button" class="btn btn-default" value="-" @click="cart.num -= 1"/> <!--<input class="btn-group" type="number" v-model="cart.num" readonly="readonly" />--> {{cart.num}} <input type="button" class="btn btn-default" value="+" @click="cart.num += 1"/> </td> <td> <button class="btn btn-danger" @click="delete_num">删除</button> </td> </tr> <tr v-show="cart_list.length==0"> <td colspan="6" class="text-center text-muted"> <p>暂无数据....</p> </td> </tr> </table> <div> 总计:共 {{cart_list.length }}件商品,已选择 {{total_num}} 件 <div class="pull-right"> 合计:{{total_price}}元 <input type="button" class="btn btn-success" @click="payment()" :disabled="check_goods.length <= 0" value="去结算"> </div> </div> </div> <script> var vm = new Vue({ el: "#app", data: { cart_list: [{ goods_name: '小米6', goods_price: '1600', num: 2, }, { goods_name: '红米3', goods_price: '700', num: 1, }, { goods_name: '小米8', goods_price: '2800', num: 1, }], check_goods: [] //已选择的商品 }, methods: { // 商品类减减 reduce: function(cart) { if(cart.num <= 0) { cart.num = 0 } else { cart.num-- } }, // 商品累加 add_num: function(cart) { cart.num++ }, // 删除商品 delete_num: function(cart) { this.check_goods.splice(this.check_goods.indexOf(cart), 1) this.cart_list.splice(this.cart_list.indexOf(cart), 1) }, //全选 check_all: function() { if(vm.check_goods.length > 0) { vm.check_goods = [] } else { /*this.cart_list.forEach((item,index) => { this.check_goods.push(item) })*/ vm.cart_list.forEach(function(item,index){ vm.check_goods.push(item) }) } }, payment: function(){ alert("付款") } }, computed: { // 总价 total_price: function() { //let price = 0 var price = 0; /*this.check_goods.forEach(item => { // 总价 = 价格 * 数量 price += Number(item.goods_price) * Number(item.num) })*/ this.check_goods.forEach(function(item){ price += Number(item.goods_price) * Number(item.num) }) return price }, // 数量 total_num: function() { var t_num = 0; this.check_goods.forEach(function(item){ t_num += Number(item.num); }) return t_num } } }) </script> </body> </html>
效果如图