vue-admin-template动态路由怎么搭建
时间: 2023-10-12 09:12:31 浏览: 108
动态路由是指路由表在运行时动态生成,而不是在编译时生成。在 Vue.js 中,可以使用 Vue Router 实现动态路由。下面是一个简单的步骤,可以帮助你搭建一个基于 Vue-admin-template 的动态路由。
1. 安装 Vue Router
```bash
npm install vue-router --save
```
2. 在 src/router/index.js 中引入 Vue Router,并创建一个路由实例
```javascript
import Vue from 'vue';
import Router from 'vue-router';
import Layout from '@/layout';
Vue.use(Router);
export const constantRoutes = [
// 静态路由
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: 'Dashboard', icon: 'dashboard' }
}]
}
];
const createRouter = () => new Router({
mode: 'history', // 启用 history 模式
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
});
const router = createRouter();
export default router;
```
3. 在 src/store/modules/permission.js 中创建一个动态路由生成函数
```javascript
import { constantRoutes } from '@/router';
/**
* 递归过滤异步路由表,返回符合用户角色权限的路由表
* @param routes asyncRoutes
* @param roles
*/
export function filterAsyncRoutes(routes, roles) {
const res = [];
routes.forEach(route => {
const tmp = { ...route };
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles);
}
res.push(tmp);
}
});
return res;
}
/**
* 判断用户角色是否有权限访问该路由
* @param roles
* @param route
*/
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role));
} else {
return true;
}
}
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);
});
}
};
export default {
namespaced: true,
state,
mutations,
actions
};
```
4. 在 src/router/index.js 中引入动态路由生成函数,并在路由实例中使用
```javascript
import Vue from 'vue';
import Router from 'vue-router';
import Layout from '@/layout';
import store from '@/store';
Vue.use(Router);
export const constantRoutes = [
// 静态路由
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: 'Dashboard', icon: 'dashboard' }
}]
}
];
const createRouter = () => new Router({
mode: 'history', // 启用 history 模式
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
});
const router = createRouter();
// 刷新页面时重新生成动态路由
router.beforeEach(async(to, from, next) => {
const hasRoles = store.getters.roles && store.getters.roles.length > 0;
if (hasRoles) {
next();
} else {
try {
// 获取用户角色信息
const { roles } = await store.dispatch('user/getInfo');
// 生成动态路由
const accessedRoutes = await store.dispatch('permission/generateRoutes', roles);
// 添加动态路由
router.addRoutes(accessedRoutes);
next({ ...to, replace: true });
} catch (error) {
console.log(error);
}
}
});
export function resetRouter() {
const newRouter = createRouter();
router.matcher = newRouter.matcher; // reset router
}
export default router;
```
以上是一个基于 Vue-admin-template 的动态路由搭建步骤,你可以根据自己的需求进行修改和扩展。
阅读全文