生活随笔
收集整理的這篇文章主要介紹了
【vue】vue实现用户长时间不操作,提示用户登录已过期重新登录
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
vue實(shí)現(xiàn)用戶長時間不操作,提示用戶登錄已過期請重新登錄
1.實(shí)現(xiàn)思路
使用 mouseover事件來監(jiān)測是否有用戶操作頁面,然后寫一個定時器間隔特定時間檢測是否長時間未操作頁面,如果是清除token,提示登錄已過期請重新登錄
2.實(shí)現(xiàn)代碼
1.在util文件夾下創(chuàng)建一個storage.js封裝localStorage方法
export default {setItem(key, value) {value
= JSON.stringify(value
);window
.localStorage
.setItem(key
, value
)},getItem(key, defaultValue) {let value
= window
.localStorage
.getItem(key
)try {value
= JSON.parse(value
);} catch {}return value
|| defaultValue
},removeItem(key) {window
.localStorage
.removeItem(key
)},clear() {window
.localStorage
.clear()},}
2.在util文件夾下創(chuàng)建一個testing.js
每隔10s去檢查一下用戶是否過了15分鐘未操作頁面
因?yàn)槲疫@邊是單點(diǎn)登錄所以用戶15分鐘未操作就要跳轉(zhuǎn)到單點(diǎn)登錄系統(tǒng),所以跳轉(zhuǎn)這一塊按實(shí)際情況來修改
import storage
from '@/utils/storage'
import {PcCookie
,Key
} from '@/utils/cookie'let lastTime
= new Date().getTime()
let currentTime
= new Date().getTime()
let timeOut
= 15 * 60 * 1000 window
.onload = function () {window
.document
.onmousedown = function () {storage
.setItem("lastTime", new Date().getTime())}
};function checkTimeout() {currentTime
= new Date().getTime() lastTime
= storage
.getItem("lastTime");if (currentTime
- lastTime
> timeOut
) { storage
.clear()PcCookie
.remove(Key
.accessTokenKey
)PcCookie
.remove(Key
.userInfoKey
)let isLock
= true if(isLock
&& PcCookie
.get(Key
.refreshTokenKey
)) {isLock
= false window
.location
.href
= `${process.env.VUE_APP_AUTH_CENTER_URL}/refresh?redirectURL=${window.location.href}`}else {window
.location
.href
= `${process.env.VUE_APP_AUTH_CENTER_URL}?redirectURL=${window.location.href}`}}
}export default function () {window
.setInterval(checkTimeout
, 10000);
}
3.在main.js引入testing.js
import Testing
from '@/utils/testing'Vue
.use(Testing
)
3.實(shí)現(xiàn)效果
總結(jié)
以上是生活随笔為你收集整理的【vue】vue实现用户长时间不操作,提示用户登录已过期重新登录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。