服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - Vue利用localStorage本地缓存使页面刷新验证码不清零功能的实现

Vue利用localStorage本地缓存使页面刷新验证码不清零功能的实现

2021-09-14 16:41文化沙漠麦七 JavaScript

这篇文章主要介绍了Vue利用localStorage本地缓存使页面刷新验证码不清零功能的实现,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

今天我们使用本地缓存localStorage来实现页面刷新了,验证码倒计时还是和刷新时一样,而不是清零,其次我们可以使用localStorage去实现用户信息缓存,记住密码等等关于缓存的功能,在这里就简单演示一下验证码功能。

一、功能实现

话不多说,直接上代码

?
1
2
3
4
5
6
<template>
    <button @click="getCode()" :disabled="!show">
  <span v-show="show">发送验证码</span>
  <span v-show="!show" class="count">{{count}} s</span>
 </button>
</template>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<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写法

?
1
2
3
4
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缓存

总结

到此这篇关于Vue利用localStorage本地缓存使页面刷新验证码不清零的文章就介绍到这了,更多相关Vue页面刷新验证码不清零内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_42783654/article/details/108378132

延伸 · 阅读

精彩推荐