vue封装倒计时组件
只暴露了button的样式和自定义事件handleClick,其他的如:倒计时秒数、倒计时前和倒计时中的文字可在源码中直接修改:
效果如下:
<template>
<div>
<button :style="buttonStyle" @click="click" :disabled="init.status">
{
{ init.time }}
<span v-if="init.status">s</span> {
{init.text}}
</button>
</div>
</template>
<script>
const SENDTEXT = '已发送验证码'
const GETTEXT = '获取验证码'
const TIME = 60
const initData = {
text: GETTEXT,
time: null, // 秒数
count: TIME,
status: false
}
export default {
name:'countDown',
props: {
buttonStyle: {
type: Object,
default() {
return {}
}
}
},
data(){
return {
init: Object.assign({}, initData), // 这样写为了初始化方便,因为下边到0秒之后也要次初始化
timer: null, // 定时器标识
}
},
methods: {
click() {
this.runTime()
this.$emit('handleClick')
},
runTime() {
this.init.status = true
this.init.text = SENDTEXT
// 下边操作的意思是:当点击按钮时,会立即出现倒计时的秒数,如果不加,
// GETTEXT已经渲染出来了,但是倒计时的秒数需等到下边异步函数执
// 行的时候才能出现, 这样用户体验很差
this.init.time = this.init.count
this.timer = setInterval(() => {
this.init.time = -- this.init.count
if(this.init.time === 0) { // 等于0时,再次初始化数据,清除定时器
this.init = Object.assign({}, initData)
clearInterval(this.timer)
}
}, 1000)
}
}
}
</script>
还没有评论,来说两句吧...