Vue Vue Router vue-element-admin 技术 Vue Router 动态加载路由后,刷新空白的问题(vue-element-admin) 2018-12-12 12:37 10240 更新于 2018-12-12 12:37 用`vue-element-admin`写后台,需要动态加载路由,实现后,发现在动态加载的路由页面,刷新页面,会跳转到自定义的404页面,而不是在当前页面 这是因为 vuex 中 sotre 存储的内容会在刷新页面时丢失 查看Vue Router手册改为History模式也不行 router.beforeEach如下 ```js 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 { 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({ ...to, replace: true }) }) }).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() } } }) ``` 虽然将` next({ ...to, replace: true })` 改为 `next({ path: '/' })` 也能解决问题,但是体验不好,一刷新就跳转到首页,[关于next 参考](https://router.vuejs.org/zh/guide/advanced/navigation-guards.html "关于next 参考") 刷新页面时打印 to.path和from.path 都是 /,无法获取上一次路由 不过发现使用 `window.location.href` 可以获取,这就好办了 使用方法`GetUrlRelativePath`获取路由( /utils/common.js) ``` 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 } ``` 获取刷新前的访问路由 ``` const fromPath = GetUrlRelativePath(window.location.href) ``` 获取用户的权限,动态加载路由 然后跳转到刷新前的路由 ``` next({ path: fromPath }) ``` 改动后如下 ```js 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() } } }) ```