vue实现加减


Vue 实现加减功能
在 Vue 中实现加减功能可以通过数据绑定和事件处理来完成。以下是几种常见的实现方式:
基础实现(选项式 API)
<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>
组合式 API 实现
<template>
<div>
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
const increment = () => {
count.value++
}
const decrement = () => {
count.value--
}
</script>
带最小值和最大值的限制
<template>
<div>
<button @click="decrement" :disabled="count <= min">-</button>
<span>{{ count }}</span>
<button @click="increment" :disabled="count >= max">+</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
const min = ref(-10)
const max = ref(10)
const increment = () => {
if (count.value < max.value) {
count.value++
}
}
const decrement = () => {
if (count.value > min.value) {
count.value--
}
}
</script>
使用计算属性
<template>
<div>
<button @click="decrement" :disabled="isMin">-</button>
<span>{{ count }}</span>
<button @click="increment" :disabled="isMax">+</button>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const min = ref(-10)
const max = ref(10)
const isMin = computed(() => count.value <= min.value)
const isMax = computed(() => count.value >= max.value)
const increment = () => {
if (!isMax.value) {
count.value++
}
}
const decrement = () => {
if (!isMin.value) {
count.value--
}
}
</script>
带步长的实现
<template>
<div>
<button @click="changeCount(-step)">-</button>
<span>{{ count }}</span>
<button @click="changeCount(step)">+</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
const step = ref(1)
const changeCount = (delta) => {
count.value += delta
}
</script>
这些示例展示了 Vue 中实现加减功能的不同方式,可以根据具体需求选择适合的方法。选项式 API 适合传统 Vue 项目,而组合式 API 更适合 Vue 3 项目。限制功能、计算属性和步长控制可以根据业务需求灵活添加。






