发送验证码按钮
<template>
<div>
<button :disabled="disable" @click="send">{{text}}</button>
</div>
</template>
实现思路:在页面初始化,从本地拿到存储的时间戳,判断是否为0。如果不为0就继续进行减1操作。
data () {
return {
text: "发送验证码",
time: 5,
timer: null,
disable: false
}
},
created () {
// 本地拿到时间
const time = localStorage.getItem('time');
// 判断是否大于0
if (time && time > 0) {
// 解决刷新页面按钮有空白情况
this.text = time + "s后重新发送"
this.time = time
this.send();
}
},
实现方法:点击按钮首先将按钮禁用防止多次点击触发定时器,然后将计数存入本地,防止刷新数据丢失。
methods: {
send () {
// 点击按钮,禁用按钮,防止多次点击
this.disable = true
this.text = this.time + "s后重新发送"
localStorage.setItem('time', this.time)
this.timer = setInterval(() => {
if (this.time > 0) {
this.time--
localStorage.setItem('time', this.time)
this.text = this.time + "s后重新发送"
} else {
clearInterval(this.timer);
this.time = 5
this.disable = false
this.text = '重新发送'
}
}, 1000)
}
}