本文参考自https://blog.jam00.com/article/info/54.html。html
最近,基于vue admin template作了个demo,在它基础上对某些菜单加了页面权限控制,可是如今刷新作了权限控制的页面后,就404了,没加权限控制的是正常的。通过一番查找,发现是由于 vuex 中 sotre 存储的内容会在刷新页面时丢失致使的。vue
虽然将 next({ ...to, replace: true }) 改成 next({ path: '/' }) 也能解决问题,可是体验很差,一刷新就跳转到首页,关于next 参考vuex
刷新页面时打印 to.path和from.path 都是 /,没法获取上一次路由app
不过发现使用 window.location.href 能够获取,这就好办了ide
使用方法GetUrlRelativePath获取路由( /utils/common.js)ui
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
}
|
获取刷新前的访问路由url
1
|
const fromPath = GetUrlRelativePath(window.location.href)
|
获取用户的权限,动态加载路由spa
而后跳转到刷新前的路由code
1
|
next({ path: fromPath })
|
改动后以下orm
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()
}
}
})
|