思路
本教程采用本地存储 localStoryge
缓存结束时间实现倒计时效果。
实现
以验证码为例:
<template>
<el-button type="primary" @click="GetCode" :disabled="!BtnStatus">
{{BtnStatus?'获取验证码':`${countDownTime}秒后获取`}}
</el-button>
</template>
点击验证码,切换状态,按钮变为倒计时,并开始计时
//...
data () {
return {
BtnStatus: true,
countDownTime: 60
}
}
//...
点击获取验证码按钮,存储点击时刻时间(毫秒)到本地存储。传入时间,执行倒计时函数
倒计时前更改按钮状态,计算倒计时时间(用传递的结束时间减去当前时间)
当时间小于1的时候,清除倒计时,更改按钮状态为验证码按钮,初始化倒计时,否则回调倒计时
//...
methods: {
GetCode () {
let endMsRes = (new Date()).getTime() + 60000;
//Setitem 为封装 localStoryge 方法
Setitem('myEndTime', JSON.stringify(endMsRes));
this.codeCountDown(endMsRes)
},
codeCountDown ( endMsRes) {
this.BtnStatus = false;
this.countDownTime= Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
let time = setTimeout(() => {
this.countDownTime--
if (this.countDownTime< 1) {
this.BtnStatus = true
this.countDownTime= 60
clearTimeout(time)
} else {
this.codeCountDown(endMsRes)
}
}, 1000)
}
}
//...
页面刷新的时候,利用本地存储的时间进行初始化
重新计算 countDownTime
并倒计时
//...
created () {
let myEndTime= Getitem('myEndTime')
this.codeCountDown(myEndTime)
}
//...
这样就完整的实现了倒计时功能