vue-element-admin动态生成侧边栏以及添加路由
需求:后端根据登录的用户不同,返回具体的路由表,前端根据后端返回的数据动态生成侧边栏以及实现跳转。(与该框架返回角色且根据角色生成路由不同)1、首先登陆,登陆成功之后拿token获取后端接口,把得到的数据放在localStorage里面sysHome() {this.$api.xxxxx().then(function(res) {localStorage.setItem('router', JS
·
需求:后端根据登录的用户不同,返回具体的路由表,前端根据后端返回的数据动态生成侧边栏以及实现跳转。(与该框架返回角色且根据角色生成路由不同)
1、首先登陆,登陆成功之后拿token获取后端接口,把得到的数据放在localStorage里面
sysHome() {
this.$api.xxxxx()
.then(function(res) {
localStorage.setItem('router', JSON.stringify(res.data))// 返回的数据存在localStorage里面
}).catch(function(error) {
console.log(error)
// 响应错误回调
})
},
2、在permission.js里面取路由数据,重新封装,把路由数据通过router.addRoutes方法放到全局路由对象里面(才能实现跳转),还要把路由数据放到vuex路由数据里面,因为你的侧边栏是用vuex里面的数据渲染的
import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import Layout from './layout'
import _import from './router/_import_development'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist
var getRouter
// var routerMap = new Map() // 这个不需要管,这是我获取页面按钮权限的
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.title)
// determine whether the user has logged in
if (localStorage.getItem('token')) { //判断有没有登录
if (to.path === '/login') {
// 如果已经登录了,就重定向去首页
next({ path: '/' })
NProgress.done()
} else {
if (getRouter) { // 一定要加,要不然陷入死循环
// await store.dispatch('permission/setPermission', routerMap.get(to.path.split('/').reverse()[0]))
next()
} else {
getRouter = JSON.parse(localStorage.getItem('router'))// 拿到路由
getRouter = Array.from(getRouter)// 把路由对象变为路由数组
getRouter = filterAsyncRouter(getRouter) // 过滤路由
router.addRoutes(getRouter) // 添加到全局路由
router.options.routes = getRouter
await store.dispatch('permission/generateRoutes') // 通过vuex方法,把路由数据保存在vuex的state里面
next({ ...to, replace: true })
}
}
} else {
// 如果没有登录
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
function filterAsyncRouter(asyncRouterMap) { // 遍历后台传来的路由字符串,转换为组件对象
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Layout') { // Layout组件特殊处理
route.component = Layout
} else {
route.component = _import(route.component)
}
}
// route.path = route.url
// route.meta = {}
// route.meta.title = route.title
// if (route.type === 2 && route.children) {
//route.btn = []
//route.children.forEach(e => {
// route.btn.push(e.code)
//})
// routerMap.set(route.path, route.btn)
}
if (route.children || route.children.length !== 0) {
route.children = filterAsyncRouter(route.children)
}
return true
})
return accessedRouters
}
router.afterEach(() => {
// finish progress bar
NProgress.done()
})
3、新增一个js ,router/_import_development
module.exports = file => () => import('@/views/' + file)
4、vuex方法里
import { asyncRoutes, constantRoutes } from '@/router'
import router from '@/router'
const state = {
routes: [],
addRoutes: []
}
const mutations = {
SET_ROUTES: (state) => {
state.addRoutes = router.options.routes
state.routes = constantRoutes.concat(state.addRoutes)
}
}
const actions = {
generateRoutes({ commit }) {
return new Promise(resolve => {
// const accessedRoutes = router.options.routes || []
commit('SET_ROUTES')
resolve(1)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)