今天我们使用本地缓存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>
二、知识拓展
1.对比cookies,sessionStorage 和 localStorage 三大缓存的主要区别
1)存储大小
- cookie数据大小不能超过4k。
- sessionStorage和localStorage 虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大。
2)有效时间
- localStorage:存储持久数据,浏览器关闭后数据不丢失除非主动删除数据;
- sessionStorage:数据在当前浏览器窗口关闭后自动删除。
- cookie:设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭,
3)数据与服务器之间的交互方式
- cookie的数据会自动的传递到服务器,服务器端也可以写cookie到客户端。
- sessionStorage仅在本地保存,只能在同一标签下共享。
- localStorage仅在本地保存,同一浏览器,标签页全部共享。
4)适合场景使用
- localStorage:适合用于用户离开不清除的数据,如记住密码。
- sessionStorage:适合用于做一些用户离开时及清除的数据,如用户信息。
- cookie:适合用于和服务器交互的数据,如用户发起请求的唯一凭证。
当然只是说谁更适合,存在即合理,别和我杠。
2.localStorage写法
localStorage.getItem("code")//或localStorage.code或localStorage["code"],获取code
localStorage.setItem("code","A")//或localStorage.code="A"或localStorage["code"]="A",存储code
localStorage.removeItem("code")//存储的持久数据不清除是不会丢失的,清除code
localStorage.clear(); //清除本地全部localStorage缓存
总结