今天我们使用本地缓存localStorage来实现页面刷新了,验证码倒计时还是和刷新时一样,而不是清零,其次我们可以使用localStorage去实现用户信息缓存,在这里就简单演示一下验证码功能。
话不多说,直接上代码
<template> <button @click="getCode()" :disabled="!show"> <span v-show="show">发送验证码</span> <span v-show="!show" class="count">{{count}} s</span> </button> </template> <script> let TIME_COUNT = 60; // 设置一个全局的倒计时的时间 export default { data() { return { show: true, count: '', timer: null, } }, components: { marquee }, created(){ // 进入页面时获取倒计时中止的位置,并继续计时 if (localStorage.regtime > 0 && localStorage.regtime <= TIME_COUNT){ TIME_COUNT = localStorage.regtime; this.count = TIME_COUNT; this.show = false; this.timer = setInterval(() => { if (this.count > 0 && this.count <= TIME_COUNT) { this.count-- localStorage.regtime = this.count; } else { this.show = true; clearInterval(this.timer); this.timer = null } }, 1000) } }, methods: { getCode () { // 验证码倒计时 if (!this.timer) { this.count = TIME_COUNT localStorage.regtime = this.count; this.show = false this.timer = setInterval(() => { if (this.count > 0 && this.count <= TIME_COUNT) { this.count-- localStorage.regtime = this.count; } else { this.show = true clearInterval(this.timer) this.timer = null } }, 1000) } } } </script>