<template>
<view>
<block v-for="(item, index) in cartItems" :key="item.id">
<uni-number-box v-if="item.quantity > 0" :value="item.quantity" :min="1" @minus="onMinus($event, index)" @change="onNumberChange($event, index)"></uni-number-box>
</block>
</view>
</template>
<script>
export default {
data() {
return {
cartItems: [
{ id: 1, quantity: 1 },
{ id: 2, quantity: 1 }
]
};
},
methods: {
onMinus(e, index) {
if (this.cartItems[index].quantity > 1) {
this.cartItems[index].quantity--;
} else {
// 如果数量减少到1,则将数量设置为0,而不是删除数组项
this.cartItems[index].quantity = 0;
}
},
onNumberChange(e, index) {
// 更新对应数据项的数量
this.cartItems[index].quantity = e.detail.value;
}
}
};
</script>
出现此类情况可能是步进器的状态复用问题,可能是因为uni-number-box
组件在列表更新时没有正确地响应数据变化。使用v-if
来控制组件的显示和隐藏:而不是在数据变化时删除数组中的项,可以使用v-if
来控制组件的显示和隐藏。这样,当数量为0时,组件会被完全销毁和重新创建,从而避免了状态复用的问题。