vue实现加减条
Vue 实现加减条
在 Vue 中实现加减条(即数字增减组件)可以通过数据绑定和事件处理来完成。以下是一个简单的实现方式:
模板部分
<template>
<div class="counter">
<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() {
if (this.count > 0) {
this.count--
}
}
}
}
</script>
样式部分
<style scoped>
.counter {
display: flex;
align-items: center;
gap: 10px;
}
button {
padding: 5px 10px;
cursor: pointer;
}
</style>
带最小值和最大值的加减条
如果需要限制最小值和最大值,可以修改方法逻辑:
methods: {
increment() {
if (this.count < this.max) {
this.count++
}
},
decrement() {
if (this.count > this.min) {
this.count--
}
}
},
props: {
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 10
}
}
可复用的组件版本
创建一个可复用的计数器组件:
<template>
<div class="counter">
<button @click="change(-step)" :disabled="count <= min">-</button>
<span>{{ count }}</span>
<button @click="change(step)" :disabled="count >= max">+</button>
</div>
</template>
<script>
export default {
props: {
value: Number,
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: Infinity
},
step: {
type: Number,
default: 1
}
},
data() {
return {
count: this.value
}
},
methods: {
change(delta) {
const newValue = this.count + delta
if (newValue >= this.min && newValue <= this.max) {
this.count = newValue
this.$emit('input', newValue)
}
}
},
watch: {
value(newVal) {
this.count = newVal
}
}
}
</script>
使用时可以这样:
<counter v-model="quantity" :min="1" :max="10" :step="2" />
这些实现方式提供了基本的加减功能,可以根据需要进一步扩展样式和功能。







