基于vue-admin-template开发的项目,在加了基于角色的权限控制后,刷新页面就跳404
本文参考自https://blog.jam00.com/article/info/54.html。
最近,基于vue admin template做了个demo,在它基础上对某些菜单加了页面权限控制,但是现在刷新做了权限控制的页面后,就404了,没加权限控制的是正常的。经过一番查找,发现是因为 vuex 中 sotre 存储的内容会在刷新页面时丢失导致的。
虽然将 next({ ...to, replace: true }) 改为 next({ path: '/' }) 也能解决问题,但是体验不好,一刷新就跳转到首页,关于next 参考
刷新页面时打印 to.path和from.path 都是 /,无法获取上一次路由
不过发现使用 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
}
|
获取刷新前的访问路由
1 |
const fromPath = GetUrlRelativePath(window.location.href) |
获取用户的权限,动态加载路由
然后跳转到刷新前的路由
1 |
next({ path: fromPath }) |
改动后如下
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 => { // 拉取用户信息
const roles = res.data.roles
store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可访问的路由表
router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
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}`) // 否则全部重定向到登录页
NProgress.done()
}
}
})
|