动态路由踩坑指南

一、动态路由添加没反应

动态路由的添加一般是在permission.js文件中 vue router导航守卫中进行配置,添加动态路由

router.beforeEach((to, from, next) => {NProgress.start()if (getToken()) {/* has token*/if (to.path === '/login') {next({ path: '/' })NProgress.done()} else {if (store.getters.roles.length === 0) {// 判断当前用户是否已拉取完user_info信息store.dispatch('GetInfo').then(() => {store.dispatch('GenerateRoutes').then(accessRoutes => {// 根据roles权限生成可访问的路由表router.addRoutes(accessRoutes) // 动态添加可访问路由表next({ ...to, replace: true }) // hack方法 确保addRoutes已完成})}).catch(err => {store.dispatch('LogOut').then(() => {Message.error(err)next({ path: '/' })})})} else {next()}}} else {// 没有tokenif (whiteList.indexOf(to.path) !== -1) {// 在免登录白名单,直接进入next()} else {next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页NProgress.done()}}
})

主要是通过router.addRoutes()进行动态路由的添加,但是只更改这个地方可能不会使动态路由生效,还需要更改layout/Sidebar/index里的菜单取值为动态路由添加后的值

//更改前
export default {components: { SidebarItem, Logo },computed: {...mapGetters(['sidebar']),routes() {return this.$router.options.routes},activeMenu() {const route = this.$routeconst { meta, path } = route// if set path, the sidebar will highlight the path you setif (meta.activeMenu) {return meta.activeMenu}return path},showLogo() {return this.$store.state.settings.sidebarLogo},variables() {return variables},isCollapse() {return !this.sidebar.opened}}
}//更改后  菜单渲染的取值也又routes改为sidebarRouters
export default {components: { SidebarItem, Logo },computed: {...mapGetters(["sidebarRouters", "sidebar"]),activeMenu() {const route = this.$routeconst { meta, path } = route// if set path, the sidebar will highlight the path you setif (meta.activeMenu) {return meta.activeMenu}return path},showLogo() {return this.$store.state.settings.sidebarLogo},variables() {return variables},isCollapse() {return !this.sidebar.opened}},created(){console.log(this.sidebarRouters);}
}

二、页面一刷新就跳转404页面

研究了半天才发现是静态路由的配置问题,404页面的重定向不能放到静态路由里,要放到动态路由中

// 生成路由GenerateRoutes({ commit, state }) {return new Promise(resolve => {// 向后端请求路由数据// getRouters().then(res => {const sdata = JSON.parse(JSON.stringify(state.oldRoutes))const rdata = JSON.parse(JSON.stringify(state.oldRoutes))const sidebarRoutes = filterAsyncRouter(sdata)const rewriteRoutes = filterAsyncRouter(rdata, false, true)rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })commit('SET_ROUTES', rewriteRoutes)commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))commit('SET_DEFAULT_ROUTES', sidebarRoutes)commit('SET_TOPBAR_ROUTES', sidebarRoutes)resolve(rewriteRoutes)// })})}

三、添加非system文件夹下的动态路由,找不到文件

最开始搜索了好长时间都没有找到解决方案,后来灵机一动停止服务重新运行一下,没想到竟然没问题了🤣🤣🤣


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部