本文实例为大家分享了Vue在购物车场景下的应用,供大家参考,具体内容如下
购物车场景需求:
1. 商品、店铺、购物车的选择
2. 商品删除
关键代码
测试数据
var _list = [{ checked: false, goods: [{ name: "商品1", price: 23, checked: false }] }, { checked: false, goods: [{ name: "商品2", price: 20, checked: false }, { name: "商品3", price: 30, checked: false }] }];
店铺对象组成购物车数组 _list
商品对象组成店铺对象下的商品数组 goods
每个商品和店铺都有自己的 checked 字段
一. 选择商品
- 选择商品
- 选择店铺下的所有商品
- 选择购物车里的所有商品
数据绑定
<body class="app"> <input type="checkbox" v-if="list.length" v-model="checkedAll"> <div v-for="(shopI, shop) in list" class="shop"> <input type="checkbox" v-model="shop.checked"> <div v-for="(goodI, good) in shop.goods" class="good"> <input type="checkbox" v-model="good.checked"> <span v-html="good.name"></span> <span v-html="good.age"></span> </div> </div> </body>
var vue = new Vue({ el: '.app', data: { list: _list } });
监听购物车全选
computed: { checkedAll: function() { return this.checkedShopsCount == this.list.length; }, checkedShopsCount: function() { var i = 0; this.list.forEach(function(item) { if (item.checked == true) i++; }); return i; } }
当店铺选择数(checkedShopsCount)等于店铺数(list.length)时,购物车全选(checkedAll)为 true
商品 & 店铺选择事件
<input type="checkbox" v-if="list.length" v-model="checkedAll" @change="setAllChecked($event)"> <div v-for="(shopI, shop) in list"> <input type="checkbox" v-model="shop.checked" @change="setGoodChecked(shop)"> <div v-for="(goodI, good) in shop.goods"> <input type="checkbox" v-model="good.checked" @change="setShopChecked(good, shop)"> <span v-html="good.name"></span> <span v-html="good.age"></span> </div> </div>
methods: { setAllChecked: function(e) { this.list.forEach(function(shop) { shop.checked = e.target.checked; shop.goods.forEach(function(good) { good.checked = e.target.checked; }); }); }, setGoodChecked: function(shop) { shop.goods.forEach(function(good) { good.checked = shop.checked; }); }, setShopChecked: function(good, shop) { if (!good.checked) { shop.checked = false; } else { // 检查店铺是否存在 checked 为 false 的商品 shop.checked = !shop.goods.find(function(good) { return !good.checked; }); } } }
内容版权声明:除非注明,否则皆为本站原创文章。