效果图:
前端页面5min无操作,弹出弹窗提示用户系统将在30s后退出,30s后系统自动退出至登录页面。
<template>
<div>
<div class="f-z-20-px">
{{ remainTime }}秒后无操作将退出
</div>
<el-dialog
title="您长时间未操作"
v-model="dialogVisible"
:close-on-click-modal="false"
:show-close="false"
@before-close="handleLogout()"
width="600px">
<p class="f-z-20-px text-center m-b-5">
为保障您的隐私,系统将
<b class="text-primary">{{ logoutTime }}</b>
秒后自动退出。
</p>
<template #footer>
<span>
<el-button @click="handleLogout()">手动退出</el-button>
<el-button type="primary" @click="continueAdk()">继续问诊</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
const router = useRouter();
const currentRoute = useRoute();
let lastTime = new Date().getTime();
let currentTime = new Date().getTime();
let timeOut = 1000 * 60 * 0.1; //设置超时时间: 5分钟
const remainTime = ref(300);//剩余时间
function checkTimeout() {
currentTime = new Date().getTime(); //更新当前时间
lastTime = localStorage.getItem("lastTime");
remainTime.value = parseInt((timeOut - (currentTime - lastTime)) / 1000);
console.log("currentTime", currentTime);
if (remainTime.value < 1) {
//超时清空lastTime缓存,退出至登录页
localStorage.removeItem("lastTime");
console.log("超时登出", lastTime);
let userInfo = localStorage.getItem("userInfoStorage");
if (router.currentRoute.value.path.includes("/login")) return; // 当前已经是登陆页时不做跳转
router.push("/login");
stopTimer();
}
}
let intervalId: NodeJS.Timeout | null = null;
function startTimer() {
if (intervalId !== null) return; // 如果已经有一个定时器在运行,则不启动新的
intervalId = setInterval(() => {
checkTimeout();
}, 1000);
}
function stopTimer() {
console.log('停止计时器全局倒计时');
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
}
//提示用户系统将退出的弹窗上的倒计时
let logoutTimerId: NodeJS.Timeout | null = null;
const logoutTime = ref(30);//自动关闭倒计时
function startLogoutTimer() {
if (logoutTimerId !== null) return; // 如果已经有一个定时器在运行,则不启动新的
logoutTimerId = setInterval(() => {
logoutTime.value--;
console.log('当前计数:', logoutTime.value);
if(logoutTime.value < 1 ){
handleLogout();
}
}, 1000);
}
function stopLogoutTimer() {
logoutTime.value = 30;
if (logoutTimerId) {
clearInterval(logoutTimerId);
logoutTimerId = null;
}
}
const dialogVisible = ref(false);
function continueAdk(){
stopLogoutTimer();
stopTimer();
startTimer();
dialogVisible.value = false;
}
function handleLogout() {
stopTimer();
stopLogoutTimer();
dialogVisible.value = false;
router.push("/login");
}
onMounted(() => {
localStorage.setItem("lastTime", new Date().getTime());
startTimer();
window.document.onmousedown = function () {
//监听点击事件,用户点击从头开始计时
localStorage.setItem("lastTime", new Date().getTime());
};
});
onBeforeUnmount(() => {
stopTimer();
});
</script>