需求描述:需要前端判断半小时没有操作退出登录功能
思路:拿到点击的最新时间 减去上次的时间 如果大于设置的时间就退出登录
<template>
<div id="app" style="height: 100%" @click="isTimeOut">
<router-view></router-view>
</div>
</template>
data() {
return {
lastTime: null, // 最后一次点击的时间
currentTime: null, // 当前点击的时间
timeOut: 1 * 60 * 60 * 1000, // 1小时
};
},
created() {
// 打开页面时,记录第一次的时间
this.lastTime = new Date().getTime();
},
methods: {
// 点击超时的点击事件
isTimeOut() {
// 记录最新一次的点击的时间
this.currentTime = new Date().getTime();
if (this.currentTime - this.lastTime > this.timeOut) {
// 判断上次最后一次点击的时间和这次点击的时间间隔是否超时 timeOut 此处超时
if (localStorage.getItem("xxx")) {
// 如果是登录状态有xxx情况下,清除localStorage和sessionStorage,并跳转到登录页
localStorage.clear();
sessionStorage.clear();
// 弹窗提示
this.$alert("您已长时间未操作,系统自动退出!请重新登录!", "警告", {
confirmButtonText: "确定",
callback: () => {
this.$router.push("/login");
},
});
} else {
// 如果是未登录状态,则更新最后点击的时间
this.lastTime = new Date().getTime();
}
} else {
// 此处没超时,则更新最后点击的时间
this.lastTime = new Date().getTime();
}
},
}