程序员的资源宝库

网站首页 > gitee 正文

localStorage倒计时实现(localstorage存储数据)

sanyeah 2024-03-31 13:09:33 gitee 16 ℃ 0 评论

思路:

1.点击时创建一个localStorage

2.并开始一个定时器。每次自减1,当定时器归0删除localStorage

3.这个localStorage的数据是创建时的时间戳(或者未来60s的时间戳

4.然后每次页面进入时,固定一个参数读取这个 localStorage的数据 - 现在的时间戳

5.这时的参数时一个负值,给他添加60s的时间(如果记录的是未来60s的时间戳,就要反过来减,得到的是一个正数,就没有以下的问题

  为什么这里要加60s:第一,两数相减是负值;

             第二,假如用户等了59s,退出再进入,获取的现在时间戳是相对于59s之后的,这时页面倒计时从59s开始,这明显荒唐,我们要的是1s,这时就需要60-59,得到我们想要的

// verifyCodeDisable布尔值:控制按钮是否禁用的状态
// time倒计时,默认0
// overtime结束的时间,默认0
// Date.parse(new Date()) / 1000获取现在的时间戳,去除后面三位0

// 生命周期
mounted() {
  let _this = this
  uni.getStorage({
    key: 'phone',
    success: function (res) {
      _this.overtime = res.data
    }
  });
  console.log("shijian:"+this.overtime)
  // 判断overtime是否存在,这里是一个时间戳,其实无所谓,不等于0就行
  if(this.overtime > 1122772662) {
    // 得到time为负数
    this.time = this.overtime - Date.parse(new Date()) / 1000
    if (this.time < 0) {
      this.time = this.time + 60
      // 按钮是否禁用
      this.verifyCodeDisable = true
      this.codedownTime()
    }
  }
methods: {
  // 定时器
  codedownTime(){
    let _this = this
    const count = setInterval(() => {
      this.time--
      if (this.time <= 0) {
        clearInterval(count)
        _this.verifyCodeDisable = false
        uni.removeStorageSync('phone')
      }
    }, 1000)
  }
  // 获取验证码事件
  sendVerifyCode() {
    let _this = this
    this.verifyCodeDisable = true
    // 初始时间,60秒
    this.time = 60
    uni.setStorage({
      key: 'phone',
      data: Date.parse(new Date()) / 1000
    })
    _this.codedownTime()
}

main.js文件(禁止手动修改localStorage的数据)

window.addEventListener('storage', (e) => {
console.log('e:', e)
  localStorage.setItem(e.key, e.oldValue) //重新赋值修改前的值
})

顺便区别localStorage和sessionStorage之间的区别

localStoragesessionStorage一样都是用来存储客户端临时信息的对象。

他们均只能存储字符串类型的对象(虽然规范中可以存储其他原生类型的对象,但是目前为止没有浏览器对其进行实现)。

localStorage生命周期是永久,这意味着除非用户显示在浏览器提供的UI上清除localStorage信息,否则这些信息将永远存在。(例子:倒计时)

sessionStorage生命周期为当前窗口或标签页,一旦窗口或标签页被永久关闭了,那么所有通过sessionStorage存储的数据也就被清空了。(例子:登录token)

 

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表