效果:
1.页面DOM
<div v-show="state.sendAuthCode" @click="getCode">发送验证码</div>
<div v-show="!state.sendAuthCode" ><span class="auth_text_blue">{{state.second}} </span>s</div>
2. 业务逻辑代码(直接复制 , 直接复制 , 直接复制 即可)
const state = reactive({
sendAuthCode: true,
second: 60,
timer: null
})
const getCode = () => {
if (state.sendAuthCode) {
state.sendAuthCode = false;
let interval = window.setInterval(function () {
setStorage(state.second);
if (state.second-- <= 0) {
state.second = 60;
state.sendAuthCode = true;
window.clearInterval(interval);
}
}, 1000);
}
}
const setStorage = (parm) => {
localStorage.setItem("dalay", parm);
localStorage.setItem("_time", new Date().getTime());
};
const getStorage = () => {
let localDelay = {};
localDelay.delay = localStorage.getItem("dalay");
localDelay.sec = localStorage.getItem("_time");
return localDelay;
}
const judgeCode = () => {
let localDelay = getStorage();
let secTime = parseInt(
(new Date().getTime() - localDelay.sec) / 1000
);
if (secTime > localDelay.delay) {
state.sendAuthCode = true;
} else {
state.sendAuthCode = false;
let _delay = localDelay.delay - secTime;
state.second = _delay;
state.timer = setInterval(() => {
if (_delay > 1) {
_delay--;
setStorage(_delay);
state.second = _delay;
state.sendAuthCode = false;
} else {
state.sendAuthCode = true;
window.clearInterval(state.timer);
}
}, 1000);
}
}
judgeCode()
|