vue实现计数器
vue实现计数器
使用选项式API实现
在Vue的选项式API中,可以通过data定义计数器变量,并在methods中定义增减方法:
<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实现
在Vue 3的组合式API中,可以使用ref和函数式编程风格:
<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>
添加边界限制
为防止计数器无限增减,可以添加最小值/最大值限制:
methods: {
increment() {
if (this.count < 10) this.count++
},
decrement() {
if (this.count > 0) this.count--
}
}
使用计算属性
当需要基于计数器派生状态时,可以使用计算属性:
computed: {
isMax() {
return this.count >= 10
},
isMin() {
return this.count <= 0
}
}
样式绑定
根据计数器状态动态改变样式:
<button
@click="decrement"
:disabled="isMin"
:class="{ 'disabled': isMin }">
-
</button>
.disabled {
opacity: 0.5;
cursor: not-allowed;
}






