vue-element-admin动态路由(权限路由)
前言
提示:vue2 + vue-element-admin动态权限路由实现
一、router/index.js下路由定义
代码如下(示例):
export const constantRoutes = [
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
}
]
二.定义权限路由
代码如下(示例):
export const asyncRoutes = [
{
path: '/example',
component: Layout,
redirect: '/example/table',
name: 'Example',
meta: { title: 'Example', icon: 'el-icon-s-help' },
alwaysShow: true,
children: [
{
path: 'table',
name: 'Table',
component: () => import('@/views/table/index'),
meta: {
title: 'Table',
icon: 'table'
}
},
{
path: 'tree',
name: 'Tree',
component: () => import('@/views/tree/index'),
meta: {
title: 'Tree',
icon: 'tree'
}
}
]
},
{
path: '/form',
component: Layout,
children: [
{
path: 'index',
name: 'Form',
component: () => import('@/views/form/index'),
meta: {
title: 'Form',
icon: 'form'
}
}
]
},
{
path: '/nested',
component: Layout,
redirect: '/nested/menu1',
name: 'Nested',
alwaysShow: true,
meta: {
title: 'Nested',
icon: 'nested'
},
children: [
{
path: 'menu1',
component: () => import('@/views/nested/menu1/index'),
name: 'Menu1',
meta: { title: 'Menu1' },
alwaysShow: true,
children: [
{
path: 'menu1-1',
component: () => import('@/views/nested/menu1/menu1-1'),
name: 'Menu1-1',
meta: { title: 'Menu1-1' }
},
{
path: 'menu1-2',
component: () => import('@/views/nested/menu1/menu1-2'),
name: 'Menu1-2',
meta: { title: 'Menu1-2' },
alwaysShow: true,
children: [
{
path: 'menu1-2-1',
component: () => import('@/views/nested/menu1/menu1-2/menu1-2-1'),
name: 'Menu1-2-1',
meta: { title: 'Menu1-2-1'}
},
{
path: 'menu1-2-2',
component: () => import('@/views/nested/menu1/menu1-2/menu1-2-2'),
name: 'Menu1-2-2',
meta: { title: 'Menu1-2-2' }
}
]
},
{
path: 'menu1-3',
component: () => import('@/views/nested/menu1/menu1-3'),
name: 'Menu1-3',
meta: { title: 'Menu1-3' }
}
]
},
{
path: 'menu2',
component: () => import('@/views/nested/menu2/index'),
name: 'Menu2',
meta: { title: 'menu2' }
}
]
},
{
path: 'external-link',
component: Layout,
children: [
{
path: 'https:
meta: { title: 'External Link', icon: 'link' }
}
]
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: {
title: 'Dashboard',
icon: 'dashboard'
}
}]
},
{ path: '*', redirect: '/404', hidden: true }
]
至此我们的路由定义完毕
三.在store/modules下面创建permission.js,并在store/index.js中引入
提示:用于根据权限处理路由:
代码如下(示例):
import {asyncRoutes, constantRoutes} from "@/router/index";
function hasPath(asyncRouterItem, userRouteItem) {
return asyncRouterItem.path === userRouteItem.path;
}
export function recursiveAsyncRoutes(asyncRouterList, userRouterList) {
let res = [];
asyncRouterList.forEach(route => {
const tmp = {...route};
if (tmp.path === '*' && !tmp.hasOwnProperty('children')) {
res.push(tmp)
} else {
userRouterList.forEach(uRoute => {
if (hasPath(tmp, uRoute)) {
if (tmp.children && uRoute.children) {
tmp.children = recursiveAsyncRoutes(tmp.children, uRoute.children)
}
res.push(tmp)
}
})
}
})
return res;
}
const state = {
hasUserRouter: false,
routes: [],
addRoutes: []
}
const mutations = {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
},
SET_ROUTER_STATE: (state, states) => {
state.hasUserRouter = states;
}
}
const actions = {
recursiveRouter({commit}, userRouterList) {
return new Promise(resolve => {
let accessedRoutes = recursiveAsyncRoutes(asyncRoutes, userRouterList);
commit('SET_ROUTES', accessedRoutes)
commit('SET_ROUTER_STATE', true)
resolve(accessedRoutes)
})
},
removeRouterState({commit}) {
commit('SET_ROUTER_STATE', false);
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import permission from './modules/permission'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
settings,
user,
permission
},
getters
})
export default store
四.找到store/modules下的user.js新增如下方法
代码如下(示例):
- state中新增字段menus,用于存放获取的权限列表
const getDefaultState = () => {
return {
token: getToken(),
name: '',
avatar: '',
menus: [],
}
}
- mutations中新增方法SET_MENUS,用于修改state中menus变量
const mutations = {
RESET_STATE: (state) => {
Object.assign(state, getDefaultState())
},
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_MENUS: (state,menus) => {
state.menus = menus
}
}
3.actions中新增getMenus方法,用于接口请求获取权限列表
getMenus({commit, state}){
return new Promise((resolve, reject)=>{
const roles = [
{
path: '/example',
children: [
{ path: 'table', },
{ path: 'tree', }
]
},
{
path: '/form',
children: [
{ path: 'index', }
]
},
{
path: '/nested',
children: [
{
path: 'menu1',
children: [
{ path: 'menu1-1' },
{ path: 'menu1-2',
children: [
{ path: 'menu1-2-1' },
{ path: 'menu1-2-2' }
]
},
{ path: 'menu1-3' }
]
},
{ path: 'menu2' }
]
},
{ path: 'external-link' },
{ path: '/' },
]
commit('SET_MENUS', roles)
resolve(roles)
})
},
五.找到src下面的permission.js文件修改try中的代码,如下
代码如下(示例):
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
const hasGetUserInfo = store.getters.name
if (hasGetUserInfo) {
next()
} else {
try {
store.dispatch('user/getMenus').then(roles=>{
store.dispatch('permission/recursiveRouter', roles).then(res=>{
router.matcher = new Router().matcher
router.addRoutes(res)
})
})
next()
} catch (error) {
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
六.找到src/layout/components/Sidebar下的index.vue修改routes属性
代码如下(示例):
routes() {
return this.$store.state.permission.routes
},
七. 此时动态路由已经实现,但是发现this.$router.push跳转的时候会报下面该错误
解决方案:引入import { resetRouter } from '@/router',并在this.$router.push前调用resetRouter(),代码示例: 如下(这里最好封装统一路由跳转方法)
总结
至此vue2 + vue-element-admin动态路由权限完美实现!
本文为本人原创,转载请注明出处!!! 如果本文对你有帮助,请留下你的大拇指吧!
|