通过vue实现数字加减
使用 Vue 实现数字加减
方法一:基础实现(Vue 2/3 通用)
在 Vue 中可以通过 v-model 绑定数据,结合按钮事件实现数字加减功能。
<template>
<div>
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
}
</script>
方法二:带最小/最大值限制
通过计算属性或方法限制数字的增减范围。

<template>
<div>
<button @click="changeCount(-1)" :disabled="count <= min">-</button>
<span>{{ count }}</span>
<button @click="changeCount(1)" :disabled="count >= max">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
min: -10,
max: 10
}
},
methods: {
changeCount(step) {
const newValue = this.count + step
if (newValue >= this.min && newValue <= this.max) {
this.count = newValue
}
}
}
}
</script>
方法三:使用 Vue 3 Composition API
Vue 3 的 Composition API 提供更灵活的代码组织方式。
<template>
<div>
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => {
count.value++
}
const decrement = () => {
count.value--
}
return {
count,
increment,
decrement
}
}
}
</script>
方法四:带输入框的双向绑定
结合输入框实现直接输入和按钮增减。

<template>
<div>
<button @click="count--">-</button>
<input type="number" v-model.number="count">
<button @click="count++">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
}
}
</script>
方法五:封装为可复用组件
将计数器逻辑封装为可复用组件。
<!-- Counter.vue -->
<template>
<div>
<button @click="decrement">-</button>
<span>{{ modelValue }}</span>
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Number,
default: 0
}
},
emits: ['update:modelValue'],
methods: {
increment() {
this.$emit('update:modelValue', this.modelValue + 1)
},
decrement() {
this.$emit('update:modelValue', this.modelValue - 1)
}
}
}
</script>
使用时通过 v-model 绑定:
<template>
<Counter v-model="count" />
</template>
<script>
import Counter from './Counter.vue'
export default {
components: { Counter },
data() {
return {
count: 0
}
}
}
</script>
以上方法可根据实际需求选择使用,从简单实现到可复用组件封装,覆盖了 Vue 2 和 Vue 3 的不同实现方式。






