vue-element-admin动态路由的实现
时间: 2024-06-19 13:02:36 浏览: 12
Vue-element-admin是一个基于Vue.js的后台管理系统解决方案。它采用了动态路由的实现方式,可以根据用户权限动态生成菜单和路由。具体的实现步骤如下:
1. 在后端将用户的权限信息返回给前端,包括路由信息和菜单信息。
2. 在前端将路由信息存储在vuex的state中,可以通过store.dispatch()将数据传递到state中。
3. 通过Vue-router提供的addRoutes()方法,根据用户权限动态生成路由。
4. 在菜单中显示对应的可用路由。
下面是一个简单的示例:
在后端返回的路由信息中包含如下格式的数据:
```
{
path: '/dashboard',
component: Layout,
redirect: '/dashboard/index',
children: [
{
path: 'index',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: 'Dashboard', icon: 'dashboard' }
}
]
}
```
在前端可以通过以下代码将路由信息存储到vuex中:
```
import { asyncRoutes, constantRoutes } from '@/router'
const state = {
routes: [], // 存储最终可用的路由
addRoutes: [] // 存储根据用户权限动态生成的路由
}
const mutations = {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
}
const actions = {
generateRoutes({ commit }, roles) {
return new Promise(resolve => {
let accessedRoutes
if (roles.includes('admin')) {
accessedRoutes = asyncRoutes || []
} else {
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
}
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
}
}
```
通过调用store.dispatch()方法,可以将数据传递到vuex中:
```
store.dispatch('generateRoutes', ['admin']).then(() => {
router.addRoutes(store.getters.addRoutes)
})
```
上述代码中,先调用generateRoutes()方法来根据用户权限生成路由,然后再调用addRoutes()方法将动态生成的路由添加到router中。这样就可以根据用户权限动态生成菜单和路由了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)