vue实现按钮计时
Vue 实现按钮计时功能
在 Vue 中实现按钮计时功能通常涉及倒计时逻辑和按钮状态的动态切换。以下是两种常见实现方式:
基础倒计时实现
<template>
<button @click="startCountdown" :disabled="isCounting">
{{ buttonText }}
</button>
</template>
<script>
export default {
data() {
return {
count: 60,
isCounting: false,
timer: null
}
},
computed: {
buttonText() {
return this.isCounting ? `剩余${this.count}秒` : '获取验证码'
}
},
methods: {
startCountdown() {
this.isCounting = true
this.timer = setInterval(() => {
this.count--
if (this.count <= 0) {
clearInterval(this.timer)
this.isCounting = false
this.count = 60
}
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用组件封装
创建可复用的倒计时按钮组件:
<template>
<button
:class="{ 'disabled': counting }"
@click="triggerCountdown"
:disabled="counting"
>
{{ counting ? `${count}秒后重试` : text }}
</button>
</template>
<script>
export default {
props: {
duration: {
type: Number,
default: 60
},
text: {
type: String,
default: '发送验证码'
}
},
data() {
return {
count: this.duration,
counting: false,
timer: null
}
},
methods: {
triggerCountdown() {
this.counting = true
this.$emit('click')
this.timer = setInterval(() => {
this.count--
if (this.count <= 0) {
this.resetCountdown()
}
}, 1000)
},
resetCountdown() {
clearInterval(this.timer)
this.counting = false
this.count = this.duration
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style scoped>
.disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>
使用 Composition API 实现
Vue 3 的 Composition API 版本:
<template>
<button @click="start" :disabled="isActive">
{{ isActive ? `${seconds}秒后重试` : '点击发送' }}
</button>
</template>
<script setup>
import { ref } from 'vue'
const seconds = ref(60)
const isActive = ref(false)
let timer = null
const start = () => {
isActive.value = true
timer = setInterval(() => {
seconds.value--
if (seconds.value <= 0) {
clearInterval(timer)
isActive.value = false
seconds.value = 60
}
}, 1000)
}
</script>
注意事项
- 清除定时器:务必在组件销毁时清除定时器,防止内存泄漏
- 状态重置:倒计时结束后恢复初始状态
- 禁用状态:通过 disabled 属性防止重复点击
- 样式处理:可添加过渡效果提升用户体验
以上实现可根据具体需求调整倒计时时长、按钮文本和样式表现。







