实现功能: 登录系统后,页面在一定的时间内没有操作(鼠标点击)则退出到登录页面
utils/astrict.js
// 引入路由和storage工具函数
import stroage from "./storage";
import router from "@/router";
import store from "@/store";
let lastTime = new Date().getTime();
let currentTime = new Date().getTime();
let timeOut = 1000 * 60 * 15; //设置超时时间: 15分钟
window.onload = function () {
// console.log("进入页面");
window.document.onmousedown = function () {
// console.log("设置时间", new Date().getTime());
stroage.setItem("lastTime", new Date().getTime());
};
};
function checkTimeout() {
currentTime = new Date().getTime(); //更新当前时间
lastTime = stroage.getItem("lastTime");
if (currentTime - lastTime > timeOut) {
//判断是否超时
// 清除storage的lastTime
stroage.removeItem(lastTime);
// 跳到登陆页
if (router.currentRoute.value.path.includes("/login")) return; // 当前已经是登陆页时不做跳转
console.log("超时登出", lastTime);
console.log("当前路由", router.currentRoute.value);
store.dispatch("user/logout");
}
}
export default function () {
/* 定时器 间隔10秒检测是否长时间未操作页面 */
window.setInterval(checkTimeout, 10000);
}
utils/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 (e) {
console.log(e);
}
return value || defaultValue;
},
removeItem(key) {
window.localStorage.removeItem(key);
},
clear() {
window.localStorage.clear();
},
//移除多个键值对
removeItems(keys) {
keys.length && keys.map((key) => window.localStorage.removeItem(key));
}
};
Home.vue
<template>
<TLayout hasSider>
<TMenu></TMenu>
<TLayout>
<THeader></THeader>
<TContent>
<div class="layout-content block__animation" :style="panelStyle" id="layoutContent">
<router-view />
</div>
</TContent>
</TLayout>
</TLayout>
</template>
<script>
import { TLayout, TMenu, TContent, THeader } from "../components/layout";
import { defineComponent, onMounted, onBeforeUnmount, computed } from "vue";
import { useStore } from "vuex";
import astrictTime from "@/utils/astrict";
import stroage from "@/utils/storage";
export default defineComponent({
name: "Home",
components: {
TLayout,
TMenu,
TContent,
THeader
},
setup() {
const store = useStore();
const panelStyle = computed(() => ({
"min-width": store.state.user.toggle ? "1184px" : "1352px"
}));
let timer = null;
onMounted(() => {
stroage.setItem("lastTime", new Date().getTime());
// console.log("Home Mounted", new Date().getTime());
timer = astrictTime();
});
onBeforeUnmount(() => {
window.clearInterval(timer);
});
return {
panelStyle
};
}
});
</script>
<style lang="less" scoped>
.layout-content {
min-width: 600px;
height: 100%;
overflow-y: auto;
scroll-behavior: smooth;
&::-webkit-scrollbar-thumb {
background: transparent;
}
&:hover {
&::-webkit-scrollbar-thumb {
background: #c9cdd4;
}
}
}
</style>