优化<template> <div class="number-container d-flex justify-content-center align-items-center"> <!-- 减 1 的按钮 --> <button type="button" class="btn btn-light btn-sm" @click="sub">-</button> <!-- 购买的数量 --> <span class="number-box">{{ num }}</span> <!-- 加 1 的按钮 --> <button type="button" class="btn btn-light btn-sm" @click="add">+</button> </div> </template> <script> import bus from '@/components/eventBus.js' export default { props: { // 接收到的商品数量 num: { type: Number, default: 1 }, //接收商品的 id 值 //期望使用 EventBus 方案,把数量传递到 App.vue 的时候,需要通知 App 组件,更新哪个商品的数量 id: { type: Number, required: true } }, methods: { //要发送给 App 的数据格式为 { id, value };其中id是商品的 id,value 是商品最新的购买数量 //数量增减 add() { const obj = { id: this.id, num: this.num + 1, } //num是props,this.num+1并没有修改num的原值,所以没问题 bus.$emit('share', obj) }, sub() { if (this.num - 1 === 0) return const obj = { id: this.id, value: this.num - 1 } bus.$emit('share', obj) } } } </script> <style lang="less" scoped> .number-box { min-width: 30px; text-align: center; margin: 0 5px; font-size: 12px; } .btn-sm { width: 30px; } </style> <!-- 1、App.vue -> Goods.vue 2、Goods.vue -> Count.vue -->
时间: 2023-12-03 22:44:28 浏览: 26
可以在 Count.vue 中进一步优化代码,使用计算属性来实现数量的增减:
```
<template>
<div class="number-container d-flex justify-content-center align-items-center">
<!-- 减 1 的按钮 -->
<button type="button" class="btn btn-light btn-sm" @click="sub">-</button>
<!-- 购买的数量 -->
<span class="number-box">{{ count }}</span>
<!-- 加 1 的按钮 -->
<button type="button" class="btn btn-light btn-sm" @click="add">+</button>
</div>
</template>
<script>
import bus from '@/components/eventBus.js'
export default {
props: {
// 接收到的商品数量
num: {
type: Number,
default: 1
},
// 接收商品的 id 值
// 期望使用 EventBus 方案,把数量传递到 App.vue 的时候,需要通知 App 组件,更新哪个商品的数量
id: {
type: Number,
required: true
}
},
computed: {
// 计算属性来获取 count
count() {
return this.num
}
},
methods: {
// 要发送给 App 的数据格式为 { id, num }; 其中 id 是商品的 id, num 是商品最新的购买数量
// 数量增减
add() {
const obj = {
id: this.id,
num: this.count + 1,
}
bus.$emit('share', obj)
},
sub() {
if (this.count - 1 === 0) return
const obj = {
id: this.id,
num: this.count - 1
}
bus.$emit('share', obj)
}
}
}
</script>
<style lang="less" scoped>
.number-box {
min-width: 30px;
text-align: center;
margin: 0 5px;
font-size: 12px;
}
.btn-sm {
width: 30px;
}
</style>
```
通过计算属性 count 来获取 num 的值,而不是直接访问 props 中的 num。这样做的好处是,在 add 和 sub 方法中使用的都是 count,而不是 num,可以让代码更加清晰和易于理解。