20.检测登录状态是否过期

This commit is contained in:
xuewuerduo 2024-07-18 22:34:41 +08:00
parent 868101f146
commit 52e0e636e1
2 changed files with 79 additions and 2 deletions

View File

@ -1,5 +1,9 @@
import { createRouter, createWebHistory } from "vue-router"
import {useAdminStore} from "@/stores/admin/admin.js";
import { useAdminStore } from "@/stores/admin/admin.js";
import { ElMessage } from "element-plus";
import TimeDR from "@/utils/TimeDR.js"
import LocalDR from "@/utils/LocalDR.js"
const routes= [
{
path: "/", //http://localhost:5173/
@ -50,10 +54,25 @@ router.beforeEach((to, from, next) => {
console.log("未登录")
router.push("/login")
}
}else{
console.log("不需要身份验证")
let startTime = TimeDR.now()
let endTime = adminStore.data.exporeDate
let timeSubResult = TimeDR.timeSub(startTime,endTime)
console.log("timeSubResult:",timeSubResult)
if (timeSubResult.expire){
ElMessage.error("登录已过期,请重新登录")
LocalDR.remove("admin")
router.push("/login")
}
next()
}else{
console.log("不需要身份验证")
next()
}
})

58
src/utils/TimeDR.js Normal file
View File

@ -0,0 +1,58 @@
/*
作者: 邓瑞
版本: 1.0
网站: www.dengruicode.com
日期: 2024-04-21
*/
const TimeDR = {
now() {
let date = new Date()
let yyyy = date.getFullYear()
let MM = String(date.getMonth() + 1).padStart(2, '0')
let dd = String(date.getDate()).padStart(2, '0')
let HH = String(date.getHours()).padStart(2, '0')
let mm = String(date.getMinutes()).padStart(2, '0')
let ss = String(date.getSeconds()).padStart(2, '0')
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`
},
// 时间相减
// let startTime = "2024-04-20 11:30:00"
// let endTime = "2024-04-22 12:00:00"
// let timeSubResult = TimeDR.timeSub(startTime,endTime)
timeSub(startTime, endTime) {
let startDate = new Date(startTime)
let endDate = new Date(endTime)
let expire = false
let expireText = '距离过期还差'
let duration = endDate - startDate
if (duration < 0) {
expire = true
expireText = '已过期'
duration = -duration // 取负数时间差的绝对值
}
// 天数、小时数、分钟数、秒数
let day = Math.floor(duration / (24 * 60 * 60 * 1000))
let hour = Math.floor((duration / (60 * 60 * 1000)) % 24)
let minute = Math.floor((duration / (60 * 1000)) % 60)
let second = Math.floor(duration / 1000) % 60
return {
expire,
startDate,
endDate,
day,
hour,
minute,
second,
remark: `${expireText} ${day}${hour} 小时 ${minute} 分钟 ${second}`,
}
}
}
export default TimeDR