Vue設定長時間未操作登入自動到期返回登入頁
阿新 • • 發佈:2020-01-25
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設定長時間未操作登入自動到期返回登入頁,希望對大家有所幫助!