vue 实现数量加减
Vue 实现数量加减功能
在 Vue 中实现数量加减功能可以通过数据绑定和事件处理来实现。以下是几种常见的实现方式:
基础实现
通过 v-model 绑定数据,使用 @click 事件处理增减逻辑:

<template>
<div>
<button @click="decrement">-</button>
<input type="number" v-model="count" min="0">
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement() {
if (this.count > 0) {
this.count--
}
}
}
}
</script>
带最小值和最大值限制
添加最小值和最大值限制,防止超出范围:

<template>
<div>
<button @click="changeCount(-1)" :disabled="count <= min">-</button>
<input type="number" v-model="count" :min="min" :max="max">
<button @click="changeCount(1)" :disabled="count >= max">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
min: 0,
max: 10
}
},
methods: {
changeCount(step) {
const newValue = this.count + step
if (newValue >= this.min && newValue <= this.max) {
this.count = newValue
}
}
}
}
</script>
使用计算属性
通过计算属性来处理更复杂的逻辑:
<template>
<div>
<button @click="count = count - 1" :disabled="isMin">-</button>
<span>{{ count }}</span>
<button @click="count = count + 1" :disabled="isMax">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
min: 0,
max: 10
}
},
computed: {
isMin() {
return this.count <= this.min
},
isMax() {
return this.count >= this.max
}
}
}
</script>
封装为组件
将计数器功能封装为可复用的组件:
<!-- Counter.vue -->
<template>
<div class="counter">
<button @click="decrement" :disabled="isMin">-</button>
<input type="number" v-model="internalValue" :min="min" :max="max">
<button @click="increment" :disabled="isMax">+</button>
</div>
</template>
<script>
export default {
props: {
value: {
type: Number,
default: 0
},
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: Infinity
}
},
data() {
return {
internalValue: this.value
}
},
computed: {
isMin() {
return this.internalValue <= this.min
},
isMax() {
return this.internalValue >= this.max
}
},
methods: {
increment() {
if (!this.isMax) {
this.internalValue++
this.$emit('input', this.internalValue)
}
},
decrement() {
if (!this.isMin) {
this.internalValue--
this.$emit('input', this.internalValue)
}
}
},
watch: {
value(newVal) {
this.internalValue = newVal
}
}
}
</script>
使用示例
<template>
<div>
<Counter v-model="quantity" :min="1" :max="5" />
<p>当前数量: {{ quantity }}</p>
</div>
</template>
<script>
import Counter from './Counter.vue'
export default {
components: {
Counter
},
data() {
return {
quantity: 1
}
}
}
</script>
这些实现方式涵盖了从基础到进阶的计数器功能,可以根据具体需求选择适合的方案。






