vue实现用户长时间不操作,自动退出登录

27 篇文章 0 订阅
  1. src文件夹下新建judge文件夹
  2. 在judge文件夹下新建storage.js
export default {
  setItem (key, value) {
    value = JSON.stringify(value)
    window.localStorage.setItem(key, value)
  },
  getItem (key, defaultValue) {
    let value = window.localStorage.getItem(key)
    // try {
    value = JSON.parse(value)
    // } catch {}
    return value || defaultValue
  },
  removeItem (key) {
    window.localStorage.removeItem(key)
  },
  clear () {
    window.localStorage.clear()
  }
}

  1. 在judge文件夹下新建astrict.js
// 引入路由和storage工具函数
import storage from '@/judge/storage'
import router from '@/router'
let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
let timeOut = 30 * 60 * 1000 // 设置超时时间: 30分钟
window.onload = function () {
  window.document.onmousedown = function () {
    storage.setItem('lastTime', new Date().getTime())
  }
}
function checkTimeout () {
  currentTime = new Date().getTime() // 更新当前时间
  if (currentTime - lastTime > timeOut) { // 判断是否超时
    // 清除storage的数据(登陆信息和token)
    storage.clear()
    // 跳到登陆页
    console.log(router)
    if (router.history.current.fullPath !== '/') {
      router.push({ name: '/' })
      window.location.reload()
    } // 当前已经是登陆页时不做跳转
  }
}
export default function () {
  /* 定时器 间隔30秒检测是否长时间未操作页面 */
  window.setInterval(checkTimeout, 30000)
}

  1. 在main.js中引入
import Astrict from '@/judge/astrict'
Vue.use(Astrict)

5.重启

npm run dev
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值