vue计数器 每次加2 初始值为5 最小值为1 最大值为10
时间: 2024-02-25 09:53:31 浏览: 23
可以使用Vue的数据绑定和计算属性来实现一个计数器,每次加2,初始值为5,最小值为1,最大值为10。具体实现可以参考下面的代码:
```
<template>
<div>
<button @click="addCount">+2</button>
<span>{{ count }}</span>
</div>
</template>
<script>
export default {
data () {
return {
count: 5
}
},
computed: {
// 计算属性,根据计数器的值自动计算出新的值
newCount () {
return this.count + 2
}
},
methods: {
// 点击按钮增加计数器的值
addCount () {
if (this.count < 9) {
this.count += 2
} else {
this.count = 10
}
}
},
watch: {
// 监听计数器的值,如果超出范围则重置为最小或最大值
count (newVal) {
if (newVal < 1) {
this.count = 1
} else if (newVal > 10) {
this.count = 10
}
}
}
}
</script>
```
在这个例子中,我们使用了一个计算属性 `newCount` 来根据计数器的值自动计算出新的值。在 `addCount` 方法中,我们通过判断计数器的值是否小于 9 来决定是否增加 2,同时,如果计数器的值超出了范围,则将其重置为最小或最大值。在 `watch` 中,我们监听计数器的值,如果超出范围则重置为最小或最大值。