控制商品数量——控制商品数量加一和商品数量减一,数量为0时删除id
控制商品数据加一
- 商品数量加一:根据id查询出cart中的对应商品的信息,修改对应的num数量
addNum(gid) {
// 控制单件商品数量加一:
// 获取点击商品的ID,根据id修改对应商品的num数量
var c = JSON.parse(JSON.stringify(this.cart))
c[gid].num = c[gid].num + 1
this.cart = c
}
控制商品数量减一
- 如果当前商品的数量是1,那么就删除该商品;如果当前商品的数量大于1,那么就进行减一操作
handleSub: function (id) {
// 控制商品数量减一:先拷贝,然后再修改对应商品的数量,但是只有商品数量大于一时才允许减一,如果数量等于一,直接删除商品,最后整体覆盖
let cart = JSON.parse(JSON.stringify(this.cart))
if (cart[id].num > 1) {
cart[id].num = cart[id].num - 1
} else {
// 删除商品:删除对象的属性(商品的id)
delete cart[id]
}
this.cart = cart
}
实例
结构
<!-- 数量变更 -->
<div class="calculate">
<div class="rect" @click='handleSub(name)'>-</div>
<div class="number">{{value.num}}</div>
<div class="rect" @click='handleAdd(name)'>+</div>
</div>
完整结构
<!-- 商品列表 -->
<div class="list-title">优购生活馆</div>
<div class="ware-list">
<div :key='name' v-for='(value, name) in cart' class="ware-item">
<!-- 左侧按钮checkbox -->
<div class="choice-button">
<icon @click='toggleSingle(name)' :color="value.checked?'red':'#eee'" type='success' size='18'/>
</div>
<!-- 右侧商品信息 -->
<div class="ware-content">
<!-- 左侧图片 -->
<navigator class='ware-image'>
<img :src='value.goods_small_logo' mode="aspectFill"/>
</navigator>
<!-- 右侧商品信息 -->
<div class="ware-info">
<!-- 商品名称 -->
<navigator class='ware-title'>
{{value.goods_name}}
</navigator>
<!-- 商品价格和数量变更 -->
<div class="ware-info-btm">
<!-- 商品价格 -->
<div class="ware-price">
<span>¥</span>
{{value.goods_price}}
</div>
<!-- 数量变更 -->
<div class="calculate">
<div class="rect" @click='handleSub(name)'>-</div>
<div class="number">{{value.num}}</div>
<div class="rect" @click='handleAdd(name)'>+</div>
</div>
</div>
</div>
</div>
</div>
</div>
逻辑
methods: {
handleAdd: function (id) {
// console.log(id)
// 控制商品数量加一:先拷贝cart,然后再修改对应商品的数量,最后整体更新cart
let cart = JSON.parse(JSON.stringify(this.cart))
cart[id].num = cart[id].num + 1
this.cart = cart
},
handleSub: function (id) {
// 控制商品数量减一:先拷贝,然后再修改对应商品的数量,但是只有商品数量大于一时才允许减一,如果数量等于一,直接删除商品,最后整体覆盖
let cart = JSON.parse(JSON.stringify(this.cart))
if (cart[id].num > 1) {
cart[id].num = cart[id].num - 1
} else {
// 删除商品:删除对象的属性(商品的id)
delete cart[id]
}
this.cart = cart
},
}
打印id
效果
附:控制商品数据加一
- 商品数量加一:根据id查询出products中的对应商品的信息,修改对应的num数量
addHandle (id) {
// console.log('+' + id)
let products = [...this.products]
products.some(item => {
if (item.goods_id === id) {
// 找到了要修改数量的商品,把对应商品数量加一
item.num = item.num + 1
// 终止遍历
return true
}
})
this.products = products
// this.updateStorage()
}
附:控制商品数量减一
- 如果当前商品的数量是1,那么就删除该商品;如果当前商品的数量大于1,那么就进行减一操作
subHandle (id) {
// 商品数量减一
// console.log('-' + id)
let products = [...this.products]
let currentIndex = -1
products.some((item, index) => {
if (item.goods_id === id) {
if (item.num === 1) {
// 记录一下当前商品的索引,接下来使用该索引把商品删除即可
currentIndex = index
} else {
// 商品数量减一
item.num = item.num - 1
}
// 终止遍历
return true
}
})
// 判断是否要删除商品
if (currentIndex !== -1) {
// 删除商品
products.splice(currentIndex, 1)
}
this.products = products
}