曾经面试给问到了这样的一个题目( 节流倒计时时,刷新页面会怎么样?有什么办法解决? ),后来复习就写了一下这个小demo
<template>
<div>
<div>
{{ countrdown }}
</div>
<button @click="fn">{{ countrdown===init ? '点击发送':`${countrdown}重新发送` }}</button>
</div>
</template>
<script>
export default {
data() {
return {
init: 10, // 定义一个变量,用来做时间修改,需要和倒计时时间一样
inters: null, // 定时器
countrdown: 10 // 倒计时时间
}
}, // methods
created() {
// 实例化完成后
const self = this
if (window.sessionStorage.getItem('X_no_time') == null) {
console.log('第一次或者又过来一次')
} else {
self.countrdown = Number(window.sessionStorage.getItem('X_no_time'))
// if (!this.countrdown) {
this.toLoading()
// }
}
},
methods: {
toLoading() {
// 短信验证码发送
const self = this
self.inter = setInterval(self.fusn, 1000)
},
fusn() {
const self = this
self.countrdown--
console.log(self.countrdown, '1')
window.sessionStorage.setItem('X_no_time', self.countrdown) // 存入本地
if (window.sessionStorage.getItem('X_no_time') <= '0') {
// 等于0时清空
window.sessionStorage.removeItem('X_no_time')
}
if (self.countrdown <= 0) {
// 小于或者等于0时
self.countrdown = this.init // 重新赋值,
// 如果用户在倒计时期间关闭了浏览器下次打开也面会调用created()方法
clearInterval(self.inter)
}
}, // fusn
fn() {
if (this.countrdown !== this.init) {
console.log('点击了,但是倒计时还没结束')
return
}
console.log('倒计时完成了,可以重新发送了')
this.toLoading()
}
}
} // export default
</script>