Vue3 实现长时间未操作系统,登录过期的功能

需求

用户登录系统,设置超时时间为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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值