vue实现点击加减
实现点击加减功能
在Vue中实现点击加减功能可以通过数据绑定和事件处理来完成。以下是一个简单的实现方式:
<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="decrement" :disabled="count <= min">-</button>
<span>{{ count }}</span>
<button @click="increment" :disabled="count >= max">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
min: 0,
max: 10
}
},
methods: {
increment() {
if (this.count < this.max) {
this.count++
}
},
decrement() {
if (this.count > this.min) {
this.count--
}
}
}
}
</script>
使用计算属性优化
可以使用计算属性来判断按钮是否禁用:
<template>
<div>
<button @click="decrement" :disabled="isMin">-</button>
<span>{{ count }}</span>
<button @click="increment" :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
}
},
methods: {
increment() {
if (!this.isMax) {
this.count++
}
},
decrement() {
if (!this.isMin) {
this.count--
}
}
}
}
</script>
自定义步长
可以添加步长参数来控制每次加减的数值:

<template>
<div>
<button @click="decrement" :disabled="isMin">-</button>
<span>{{ count }}</span>
<button @click="increment" :disabled="isMax">+</button>
</div>
</template>
<script>
export default {
props: {
step: {
type: Number,
default: 1
},
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 10
}
},
data() {
return {
count: this.min
}
},
computed: {
isMin() {
return this.count <= this.min
},
isMax() {
return this.count >= this.max
}
},
methods: {
increment() {
if (!this.isMax) {
this.count += this.step
}
},
decrement() {
if (!this.isMin) {
this.count -= this.step
}
}
}
}
</script>
封装为组件
可以将计数器封装为可复用的组件:
<template>
<div>
<button @click="decrement" :disabled="isMin">-</button>
<span>{{ modelValue }}</span>
<button @click="increment" :disabled="isMax">+</button>
</div>
</template>
<script>
export default {
name: 'Counter',
props: {
modelValue: {
type: Number,
required: true
},
step: {
type: Number,
default: 1
},
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 10
}
},
computed: {
isMin() {
return this.modelValue <= this.min
},
isMax() {
return this.modelValue >= this.max
}
},
methods: {
increment() {
if (!this.isMax) {
this.$emit('update:modelValue', this.modelValue + this.step)
}
},
decrement() {
if (!this.isMin) {
this.$emit('update:modelValue', this.modelValue - this.step)
}
}
}
}
</script>
使用组件时:
<template>
<Counter v-model="count" :min="0" :max="10" :step="1" />
</template>
<script>
import Counter from './Counter.vue'
export default {
components: {
Counter
},
data() {
return {
count: 0
}
}
}
</script>






