vue router 添加动态路由,路由正常跳转,F5刷新后变空白页
题目来源及自己的思路
相关代码
router.beforeEach((to, from, next) => {
NProgress.start()
if (getToken()) {
initMenu(router, store)
if (to.path === '/login') {
next({ path: '/' })
NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
} else {
next()
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next('/login')
NProgress.done()
}
}
})
export const initMenu = (router, store) => {
if (store.state.security.routes.length > 0) {
return null
}
if (!util.getObjArr('router')) {
return null
} else {
var getRouter = formatRoutes(util.getObjArr('router'))// 动态路由
getRouter.push({ path: '*', redirect: '/404', hidden: true })
const newRouter = constantRouterMap.concat(getRouter)
router.addRoutes(newRouter)
console.log(newRouter)
store.commit(types.SET_ROUTES, newRouter)
}
}
export const formatRoutes = (routes) => {
const fmRoutes = []
routes.forEach(router => {
const path = router.path
let component
if (router.component === 'Layout') {
component = Layout
} else {
component = _import(router.component)
}
const name = router.name
const icon = router.icon
let children = router.children
if (children && children instanceof Array) {
children = formatRoutes(children)
}
var fmRouter = {
path: path,
component: component,
name: name,
// icon: icon,
meta: { title: name, icon: icon },
children: children
}
fmRoutes.push(fmRouter)
})
return fmRoutes
}
你期待的结果是什么?实际看到的错误信息又是什么?
router.addRoutes(newRouter)后需要next({ ...to, replace: true })