自定义组件 vue计数器 每次加2 初始值为5 最小值为1 最大值为10
时间: 2024-02-25 17:53:34 浏览: 20
要实现一个自定义的计数器组件,可以将上面的代码封装成一个单独的组件。具体实现可以参考下面的代码:
```
<template>
<div>
<button @click="addCount">+2</button>
<span>{{ count }}</span>
</div>
</template>
<script>
export default {
// 定义组件的属性
props: {
initValue: {
type: Number,
default: 5
},
minValue: {
type: Number,
default: 1
},
maxValue: {
type: Number,
default: 10
}
},
data () {
return {
count: this.initValue
}
},
computed: {
// 计算属性,根据计数器的值自动计算出新的值
newCount () {
return this.count + 2
}
},
methods: {
// 点击按钮增加计数器的值
addCount () {
if (this.count < this.maxValue - 1) {
this.count += 2
} else {
this.count = this.maxValue
}
}
},
watch: {
// 监听计数器的值,如果超出范围则重置为最小或最大值
count (newVal) {
if (newVal < this.minValue) {
this.count = this.minValue
} else if (newVal > this.maxValue) {
this.count = this.maxValue
}
}
}
}
</script>
```
在这个例子中,我们使用了 `props` 来定义组件的属性,包括 `initValue`、`minValue` 和 `maxValue`。在 `data` 中,我们将计数器的初始值设置为 `initValue`。在 `addCount` 方法中,我们根据 `maxValue` 来判断是否增加 2,同时,如果计数器的值超出了范围,则将其重置为最小或最大值。在 `watch` 中,我们监听计数器的值,如果超出范围则重置为最小或最大值。
使用这个自定义组件时,只需要在父组件中引入并传递相应的属性即可,如下所示:
```
<template>
<div>
<custom-counter :init-value="5" :min-value="1" :max-value="10"></custom-counter>
</div>
</template>
<script>
import CustomCounter from './CustomCounter.vue'
export default {
components: {
CustomCounter
}
}
</script>
```
在这个例子中,我们通过 `:init-value`、`:min-value` 和 `:max-value` 来传递相应的属性值。