VUE倒计时组件
常用于发送短信、邮件后1分钟倒计时,倒计时结束后又可以再次点击
vue组件封装:
<template>
<div class="timer-btn">
<button
class="sendSmsBtn"
:class="disabled?'disableSendSmsBtn':''"
type="button"
@click="run"
:disabled="disabled || time > 0"
>{{ text }}</button>
</div>
</template>
<script>
export default {
name: 'TTimer',
props: {
second: {
type: Number,
default: 60
},
start: {
type: Boolean,
default: false,
}
},
watch: {
start(status) {
if (status) {
this.go()
}
},
},
data() {
return {
time: 0,
disabled: false
}
},
computed: {
text() {
return this.time > 0 ? `${this.time}s 后重获取` : '获取验证码'
}
},
methods: {
run() {
this.$emit('click')
},
go() {
this.time = this.second
this.disabled = true
this.timer()
},
timer() {
if (this.time > 0) {
this.time--
setTimeout(this.timer, 1000)
} else {
this.disabled = false
this.$emit('end')
}
}
}
}
</script>
<style lang="scss" scoped>
.timer-btn {
position: relative;
.sendSmsBtn {
height: 40px;
line-height: 40px;
border-radius: 4px;
font-size:14px;
background-color:#ecf5ff;
border: 1px solid #b3d8ff;
padding: 0 6px;
color: #409eff;
font-weight: 500;
display: inline-block;
width:100%;
min-width: 92px;
cursor: pointer;
}
.disableSendSmsBtn {
opacity: 0.5;
cursor: auto;
}
}
</style>
调用<t-timer v-else :second="60" @click="getCode" :start="startCountdown" @end="handleEnd"/>
我这儿用的getCode方法请求后台短信、startCountdown标志true或false状态可以开始啦, handleEnd方法用来标记倒计时结束后修改startCountdown状态
版权声明:本文为原创文章,版权归 全栈开发技术博客 所有。
本文链接:https://www.lvtao.net/dev/vue-timer.html
转载时须注明出处及本声明