一、动态路由添加没反应
动态路由的添加一般是在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 {
// 没有token
if (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.$route
const { meta, path } = route
// if set path, the sidebar will highlight the path you set
if (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.$route
const { meta, path } = route
// if set path, the sidebar will highlight the path you set
if (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文件夹下的动态路由,找不到文件
最开始搜索了好长时间都没有找到解决方案,后来灵机一动停止服务重新运行一下,没想到竟然没问题了🤣🤣🤣