您好,登錄后才能下訂單哦!
本文參考自https://blog.jam00.com/article/info/54.html。
? 最近,基于vue admin template做了個(gè)demo,在它基礎(chǔ)上對(duì)某些菜單加了頁(yè)面權(quán)限控制,但是現(xiàn)在刷新做了權(quán)限控制的頁(yè)面后,就404了,沒(méi)加權(quán)限控制的是正常的。經(jīng)過(guò)一番查找,發(fā)現(xiàn)是因?yàn)?vuex 中 sotre 存儲(chǔ)的內(nèi)容會(huì)在刷新頁(yè)面時(shí)丟失導(dǎo)致的。
??
雖然將?next({ ...to, replace: true }) 改為?next({ path: '/' }) 也能解決問(wèn)題,但是體驗(yàn)不好,一刷新就跳轉(zhuǎn)到首頁(yè),關(guān)于next?參考
刷新頁(yè)面時(shí)打印?to.path和from.path 都是 /,無(wú)法獲取上一次路由
不過(guò)發(fā)現(xiàn)使用?window.location.href 可以獲取,這就好辦了
使用方法GetUrlRelativePath獲取路由( /utils/common.js)
1 2 3 4 5 6 7 8 9 10 11 | export?function?GetUrlRelativePath(url)?{ ??var?arrUrl?=?url.split('//') ???var?start?=?arrUrl[1].indexOf('/') ??var?relUrl?=?arrUrl[1].substring(start) ???if?(relUrl.indexOf('?')?!==?-1)?{ ????relUrl?=?relUrl.split('?')[0] ??} ??return?relUrl } |
獲取刷新前的訪(fǎng)問(wèn)路由
1 | const?fromPath?=?GetUrlRelativePath(window.location.href) |
獲取用戶(hù)的權(quán)限,動(dòng)態(tài)加載路由
然后跳轉(zhuǎn)到刷新前的路由
1 | next({?path:?fromPath?}) |
改動(dòng)后如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | router.beforeEach((to,?from,?next)?=>?{ ??NProgress.start() ??if?(getToken())?{ ????if?(to.path?===?'/login')?{ ??????next({?path:?'/'?}) ??????NProgress.done()?//?if?current?page?is?home?will?not?trigger?? afterEach?hook,?so?manually?handle?it ????}?else?{ ??????const?fromPath?=?GetUrlRelativePath(window.location.href) ??????if?(store.getters.roles.length?===?0)?{ ????????store.dispatch('GetInfo').then(res?=>?{?//?拉取用戶(hù)信息 ??????????const?roles?=?res.data.roles ??????????store.dispatch('GenerateRoutes',?{?roles?}).then(()?=>?{?//?生成可訪(fǎng)問(wèn)的路由表 ????????????router.addRoutes(store.getters.addRouters)?//?動(dòng)態(tài)添加可訪(fǎng)問(wèn)路由表 ????????????next({?path:?fromPath?}) ??????????}) ????????}).catch((err)?=>?{ ??????????store.dispatch('FedLogOut').then(()?=>?{ ????????????Message.error(err?||?'Verification?failed,?please?login?again') ????????????next({?path:?'/'?}) ??????????}) ????????}) ??????}?else?{ ????????next() ??????} ????} ??}?else?{ ????if?(whiteList.indexOf(to.path)?!==?-1)?{ ??????next() ????}?else?{ ??????next(`/login?redirect=${to.path}`)?//?否則全部重定向到登錄頁(yè) ??????NProgress.done() ????} ??} }) |
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。