第八十四篇:Vue购物车(五) 商品数量的增减

2022-10-20,,,,

好家伙,

1.商品数量增减

我们把商品的数量增减独立出来,写成一个独立的组件Counter

<template>
<div class="number-container d-flex justify-content-center align-items-center">
<!-- 减 1 的按钮 -->
<button type="button" class="btn btn-light btn-sm">-</button>
<!-- 购买的数量 -->
<span class="number-box">1</span>
<!-- 加 1 的按钮 -->
<button type="button" class="btn btn-light btn-sm">+</button>
</div>
</template> <script>
export default {}
</script> <style lang="less" scoped>
.number-box {
min-width: 30px;
text-align: center;
margin: 0 5px;
font-size: 12px;
} .btn-sm {
width: 30px;
}
</style>

它长这个样子:

 

 

我们的组件关系为:

App.vue(父组件)==>Goods.vue(商品的渲染)==>Counter.vue(商品的增减)

 

嵌套关系清楚了,那么传值的步骤也清楚了

我们先在Counter添加一个进行商品数量更改的方法,随后,想办法把这个值传回到App.vue

这里的传值就是孙=>子=>父,看着都很麻烦,所以我们这里用到的传值方案是eventBus

当然了,传值时不仅仅是商品的数量,还有商品的id

Counter.vue中的props定义

props:{
isfull:{
type:Boolean,
default:true
},
amount:{
type:Number,
default:0
}
},

Goods.vue中组件调用时的传值

<Counter :num="count" :id="id"></Counter>

在Counter.vue中为button绑定点击触发add方法

<button type="button" class="btn btn-light btn-sm"
@click="add">+</button>

方法add的定义:

methods:{
add(){
//要发送给App的数据格式为{ id,value }
//其中,id是商品的id;value是商品最新的购买数量
const obj ={ id:this.id,value:this.num+1 }
//通过EventBus把obj对象,发送给App.vue组件
console.log(obj)
bus.$emit('share',obj)
    //把obj对象传到App.vue中
}
}

对了,不要忘记导入eventBus.js

import bus from '../eventBus.js'

在eventBus.js中(与App.vue平级)

import Vue from 'vue'

export default new Vue()

回到App.vue中,

添加created钩子的定义

created(){

    bus.$on('share',val=>{
if(item.id===val.id){
item.goods_count=val.value
return true
}
})
},

商品数量增减的功能就实现了,nice

第八十四篇:Vue购物车(五) 商品数量的增减的相关教程结束。

《第八十四篇:Vue购物车(五) 商品数量的增减.doc》

下载本文的Word格式文档,以方便收藏与打印。