需求
vue typescript项目,当页面30分钟未操作,用户退出登录
ts代码
app.vue页面
// 在组件中监听页面的onload事件
window.onload = function () {
window.document.onmousedown = () => {
const lastTime_onload = new Date().getTime()
localStorage.setItem('lastTime', lastTime_onload.toString())
}
}
utils文件夹 astrict.ts
import store from '@/store'
import { ElMessageBox } from 'element-plus/es'
const timeout = 1000 * 60 * 30 // 设置超时时间 10 分钟
const checkTimeOut = () => {
const nowTime = new Date().getTime()
const lastTime = parseInt(localStorage.getItem('lastTime') as string, 10)
if (nowTime - lastTime > timeout) {
clearLoginStatus()
}
}
// 清除用户的登录状态函数
function clearLoginStatus() {
// 当用户存在token时,退出登录
if (store.userStore.token) {
store.userStore.logoutAction().then(() => {
// 刷新页面
// 刷新页面
location.reload()
ElMessageBox.confirm('长时间未操作页面,请重新登录', '提示', {
showCancelButton: false,
closeOnClickModal: false,
showClose: false,
confirmButtonText: '重新登录',
type: 'warning'
})
})
}
}
export default function () {
/* 定时器 间隔5秒检测是否长时间未操作页面 */
window.setInterval(checkTimeOut, 1000 * 5)
}
main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import App from './App.vue'
import Astrict from '@/utils/astrict'
const app = createApp(App)
app.use(Astrict)
app.mount('#app')