vue实现按钮计时
实现按钮计时功能
在Vue中实现按钮计时功能可以通过以下步骤完成。这里提供一个基于Vue 2或Vue 3的实现方案,包含倒计时和禁用状态切换。
基本倒计时按钮实现
<template>
<button
:disabled="isCounting"
@click="startCountdown"
>
{{ 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="{'countdown-button': true, 'disabled': isCounting}"
:disabled="isCounting"
@click="handleClick"
>
{{ buttonText }}
</button>
</template>
<script>
export default {
props: {
duration: {
type: Number,
default: 60
}
},
data() {
return {
count: this.duration,
isCounting: false,
timer: null
}
},
computed: {
buttonText() {
return this.isCounting ? `${this.count}秒后重试` : '获取验证码'
}
},
methods: {
handleClick() {
this.$emit('click')
this.startCountdown()
},
startCountdown() {
this.isCounting = true
this.timer = setInterval(() => {
this.count--
if (this.count <= 0) {
this.resetCountdown()
}
}, 1000)
},
resetCountdown() {
clearInterval(this.timer)
this.isCounting = false
this.count = this.duration
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style scoped>
.countdown-button {
padding: 8px 16px;
background-color: #409eff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.countdown-button:hover {
background-color: #66b1ff;
}
.countdown-button.disabled {
background-color: #c0c4cc;
cursor: not-allowed;
}
</style>
使用Composition API实现(Vue3)
<template>
<button
:disabled="isCounting"
@click="startCountdown"
>
{{ buttonText }}
</button>
</template>
<script>
import { ref, computed, onBeforeUnmount } from 'vue'
export default {
props: {
duration: {
type: Number,
default: 60
}
},
setup(props) {
const count = ref(props.duration)
const isCounting = ref(false)
let timer = null
const buttonText = computed(() =>
isCounting.value ? `${count.value}秒后重试` : '获取验证码'
)
const startCountdown = () => {
isCounting.value = true
timer = setInterval(() => {
count.value--
if (count.value <= 0) {
resetCountdown()
}
}, 1000)
}
const resetCountdown = () => {
clearInterval(timer)
isCounting.value = false
count.value = props.duration
}
onBeforeUnmount(() => {
clearInterval(timer)
})
return {
count,
isCounting,
buttonText,
startCountdown
}
}
}
</script>
功能扩展建议
- 添加发送验证码的API调用逻辑,在
handleClick方法中先调用API,成功后再启动倒计时 - 添加加载状态,在API请求期间显示加载动画
- 使用本地存储保持倒计时状态,防止页面刷新后倒计时重置
- 添加声音或动画效果增强用户体验
以上实现可以根据实际项目需求进行调整,核心逻辑是通过setInterval实现倒计时功能,配合Vue的响应式系统更新UI状态。







