Vue登录后,无操作半小时后自动清除登录状态

38 篇文章 5 订阅

Vue登录后,用户无操作半小时后自动清除登录状态,如果有操作则重置过期时间为半小时后过期

在项目的页面入口文件App.vue文件中监听用户最后一次操作鼠标、键盘或滚动事件:

<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
// 登录状态使用store插件保存在客户端的localStorage中
import storage from 'store'
export default {
  name: 'App',
  computed: {
    token () {
      return storage.get('TOKEN')
    },
    uid () {
      return storage.get('UID')
    },
    userInfo () {
      return storage.get('USER_INFO')
    }
  },
  mounted () {
    document.onmousemove = this.debounce(this.resetStatus, 3000)
    document.onkeydown = this.debounce(this.resetStatus, 3000)
    document.onscroll = this.debounce(this.resetStatus, 3000)
  },
  methods: {
    // 使用防抖,对于短时间内(此处是3s)连续触发的事件,只执行最后一次
    debounce (fn, delay) {
      let timer = null
      return function () {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(fn, delay)
      }
    },
    resetStatus () { // 重置store插件自动清除时间
      if (this.token) {
        storage.set('TOKEN', this.token, new Date().getTime() + 30 * 60 * 1000)
        storage.set('UID', this.uid, new Date().getTime() + 30 * 60 * 1000)
        storage.set('USER_INFO', this.userInfo, new Date().getTime() + 30 * 60 * 1000)
      }
    }
  }
}
</script>
<style lang="less" scoped>
#app {
  min-height: 100vh;
  min-width: 1200px;
  margin: 0 auto;
}
</style>
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值