//NProgress進度條樣式,import引入 //import NProgress from 'nprogress' //import 'nprogress/nprogress.css' // NProgress Configuration 是否有轉圈效果 //NProgress.configure({ showSpinner: false }) const AUTH_WHITE_LIST = ['/login', '/401'] //白名單路由 // 路由處理--登錄驗證 router.beforeEach(async(to, from, next) => { // 開始進度條 NProgress.start() // 設置頁面標題 if (to.matched.length !== 0) { document.title = '頁面標題' + (to.meta.title === undefined ? '' : ' - ' + to.meta.title) } // 判斷是否登錄時,因為頁面刷新后內存中還沒有token信息,額外從session中判斷一次 if (!AuthUtils.isLogin()) { const sessionStore = SessionStorageUtils.getStore() store.replaceState(Object.assign({}, store.state, sessionStore)) } if (AuthUtils.isLogin()) { // 已經登錄的,不能跳到登陸頁面,跳到首頁 if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { if (to.matched.length === 0) { // to.matched.length代表是否匹配到當前要跳轉的路由 next('/404')// 未知頁面調錯誤頁 NProgress.done() } else if (to.meta && !AuthUtils.hasAuth(to.meta.auth)) { // 需要驗證當前路由否有權限,沒有跳404,有就繼續走 next('/404')// 無權限跳404 NProgress.done() } else { next() NProgress.done() } } } else { if (AUTH_WHITE_LIST.indexOf(to.path) !== -1) { //在白名單中就繼續正常走 next() } else if (to.matched.length === 0) { next('/401')// 未知頁面調錯誤也 } else { // 沒有登陸,不在白名單里,重定向到登陸頁 next(`/login?redirect=${to.path}`) NProgress.done() } } }) router.afterEach(() => { //跳轉完成,進度條結束 // 完成進度條 NProgress.done() })
關鍵字解釋:
- to.match---》to.matched數組,該數組中保存着匹配到的所有路由信息-------->用to.matched而不直接用to.meta 是因為前者只需要給較高一級的路由添加Auth(權限)即可,其下的所有子路由不必添加。
- replaceState---》修改了對應的store歷史記錄,更新store
Object.assign()
- Object.assign()----》將所有可枚舉屬性的值從一個或多個源對象復制到目標對象,然后返回目標對象
- Object.assign()---》是ES6新添加的接口,主要的用途是用來合並多個JavaScript的對象。
- Object.assign()-----》接口可以接收多個參數,第一個參數是目標對象,后面的都是源對象,assign方法將多個原對象的屬性和方法都合並到了目標對象上面,如果在這個過程中出現同名的屬性(方法),后合並的屬性(方法)會覆蓋之前的同名屬性(方法)。