vue项目 超两个小时未动,超时自动退出登录

613 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

需求:超时自动退出登录

app.vue中

methods: {
	testTime() {
            this.currentTime = new Date().getTime(); //更新当前时间
            if (this.currentTime - parseInt(localStorage.getItem('lastTime')) > this.timeOut) { //判断是否超时(超时自动退出登录)
                this.cleanAllCache();  //清除所有缓存数据
                //下面就可以按自己的方式跳转到登录页
                window.location.href = '登录页';
            }
        },
        setLastTime() {
            localStorage.setItem('lastTime', new Date().getTime().toString());//更新操作时间
        }
}
created() {
	//保存上次进去的时间戳
	this.setLastTime();
	//用定时器监听是否长时间未操作
	window.setInterval(this.testTime, 5 * 1000);
}

总结:当项目很久没关闭,长时间未操作,会自动跳回登录页重新登录。