Vue設置長時間未操作登錄以后自動到期返回登錄頁
首先我們寫在main.js文件中
import routerUtil from "@/utils/routerutil";//先將js文件在main.js中引入 routerUtil(router);
我們會在登陸成功后調用sessionUtil文件中的setSession,sessionUtil下面寫的有
import sessionUtil from '@/utils/sessionutil' sessionUtil.setSession("userInfo", '2');
在routerutil.js文件中
import sessionUtil from "./sessionutil"; const whiteList = ["/",'/logins']; // 路由白名單,不需要校驗 export default router => { router.beforeEach(async (to, from, next) => {/*在跳轉之前執行*/ const userInfo = sessionUtil.getSession("userInfo");//觸發sessionUtil中的getSession方法 if ( userInfo ) { //// } else { if (whiteList.indexOf(to.path) !== -1) { next(); } else { Message({ type: "warning", message: "用戶登錄過期,請重新登錄", duration: 1500, onClose() { next(`/`); } }); } } }); };
在sessionutil.js文件中
const sessionutil = { setSession(key,value,maxAge){ //key=userInfo value=2 maxAge='' || 可自行設置 const maxAgeTime = new Date().getTime() + 1000 * 3600; // 當前時間的+1小時 session 過期時間 try{ let data = { value, maxAge: maxAge ? maxAge : maxAgeTime } sessionStorage.setItem(typeof key === 'string'?key: JSON.stringify(key),JSON.stringify(data)) }catch(err){ } }, getSession(key){ try{ const maxAgeTime = new Date().getTime() + 1000 * 3600; // 首先先設置一個 session 過期時間 1H后可自行設置 let date = new Date().getTime(); //當前時間 let session = JSON.parse(sessionStorage.getItem(typeof key === 'string'?key: JSON.stringify(key))); if(session && session.maxAge != null && session.maxAge-date > 0 && session.maxAge <= maxAgeTime ){ this.setSession(key,session.value); return session.value; } else { return null; } }catch(err){ } }, } export default sessionutil;
總結
以上所述是小編給大家介紹的Vue設置長時間未操作登錄自動到期返回登錄頁,希望對大家有所幫助!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。