需求
用户登录系统,设置超时时间为15分钟,用户超过15分钟未操作页面,则在15分钟后再次点击页面的时候出现退出登录提示,点击跳转到登录页。
大致思路
登录成功后记录时间(记为上一次点击),后面每次点击的时候都获取一次当前的时间,将当前时间减去上一次点击页面的时间,如果小于15分钟,就用当前的时间替换掉上一次点击的时间,大于15分钟就退出登录。
代码
App.vue
<template>
<router-view @click="isTimeout" />
</template>
<script setup name="App">
import { onMounted, ref } from "vue";
import { ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
const lastTime = ref(null);
const timeout = ref(1000 * 60 * 15); // 设置15分钟过期
onMounted(() => {
lastTime.value = new Date().getTime();
});
function isTimeout() {
let currentTime = new Date().getTime();
// 判断之前最后一次点击的时间和这次点击的时间间隔
if (currentTime - lastTime.value > timeout.value) {
ElMessageBox.confirm("登录状态已过期。请留在本页面或重新登录。", "", {
confirmButtonText: "再次登录",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
// 这里执行退出登录操作
})
.catch(() => {});
} else {
// 如果在超时时间内点击,则这次点击的时间覆盖掉之前存的最后一次点击的时间
lastTime.value = currentTime;
}
}
</script>