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

  1. 在 util 文件夹下创建一个 auto_loginout.js 文件

    import router from '@/router'
    export default function () {
        let setInterval = null;//定时器
        let timeOut = 10 * 1000 // 设置超时时间: 10秒钟
        // console.log("开始", new Date().getTime())
        // 初次向sessionStorage存入操作时间
        window.sessionStorage.setItem('lastTime', new Date().getTime())
        // 每次操作页面,更新sessionStorage存入的操作时间
        window.onload = function () {
            window.document.onmousedown = function () {
                // console.log("开始", new Date().getTime())
                window.sessionStorage.setItem('lastTime', new Date().getTime())
            }
        }
        function checkTimeout() {
            let currentTime = new Date().getTime() // 当前时间
            let lastTime = window.sessionStorage.getItem("lastTime")//上次操作的时间
            // 判断是否超时
            if (currentTime - lastTime >= timeOut) {
                // console.log("结束", new Date().getTime())
                // 清除定时器
                window.clearInterval(setInterval);
                // 清除sessionStorage
                window.sessionStorage.clear('lastTime')
                // 跳到登陆页
                if (router.history.current.fullPath !== '/' && router.history.current.fullPath !== '/login') {
                    router.push("/login")
                    window.location.reload()
                }
            }
        }
        /* 定时器 间隔2秒检测是否长时间未操作页面 */
        setInterval = window.setInterval(checkTimeout, 2000)
    }
    
  2. main.js 中引用,通过全局方法 Vue.use() 使用

    // 自动退出文件路径
    import auto_loginout from '@/util/auto_loginout.js'
    Vue.use(auto_loginout)
    
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值