在一些管理系统中 需做到在没有权限时,连页面都没有,而不是由路由守卫做跳转;
所以就会用到addRoutes 这个api,对路由进行添加操作,下面是具体方式:
新建router文件夹、config文件夹;在两个文件夹下分别创建routerConfig.js文件;
router > index.js
import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap } from '@/config/routerConfig' //引入基础路由
Vue.use(Router)
export default new Router({
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: constantRouterMap
});
config> routerConfig.js
/**
* 基础路由
*/
export const constantRouterMap = [
{
path: '/',
redirect: { name: "login" },
hidden: true,
component: resolve => require(["@/components/home.vue"], resolve),
children: [
{
path: 'login',
name: 'login',
component: resolve => require(["@/components/login.vue"], resolve)
}
]
}
]
创建home页面 login页面
home.vue
<template>
<div id="home">
<router-view></router-view>
</div>
</template>
login.vue
<template>
<div id="login">
<button @click='getRoutes'>获取路由</button>
<button @click='goPage'>前往cs2</button>
</div>
</template>
<script>
import { Cs1, Cs2, Cs3,Ts } from '@/components'
import router from '@/router'
const routes = [
{
path: 'cs1',
name: 'cs1',
key:'cs1',
title:'cs1',
redirect: '',
hidden: true,
component: 'cs1',
children: [
{
path: 'cs2',
name: 'cs2',
key:'cs2',
title:'cs2',
component: 'cs2',
},
{
path: 'cs3',
name: 'cs3',
key:'cs3',
title:'cs3',
component: 'cs3',
}
]
},
{
path: 'ts',
name: 'ts',
key:'ts',
title:'ts',
redirect: '',
hidden: true,
component: 'ts',
}
];
//引入组件 每一个组件都要用于下方constantRouterComponents方法 动态匹配路由component 对象
const constantRouterComponents = {
cs1: Cs1,
cs2: Cs2,
cs3: Cs3,
ts:Ts
}
export default {
name: 'login',
methods:{
getRoutes(){
let list2 = this.getList(routes);
router.addRoutes(list2)
},
getList(routerMap, parent){
let that = this;
// 返回一个map对象
return routerMap.map(item => {
const currentRouter = {
// 路由地址 动态拼接生成如 /dashboard/workplace
path: `${parent && parent.path || ''}/${item.key}`,
// 路由名称
name: item.name || item.key || '',
// 该路由对应页面的组件
component: constantRouterComponents[item.component || item.key],
// meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉)
meta: { title: item.title}
}
// 为了防止出现后端返回结果不规范,处理有可能出现拼接出两个 反斜杠
currentRouter.path = currentRouter.path.replace('//', '/')
// 路由重定向
item.redirect && (currentRouter.redirect = item.redirect)
// 子菜单递归循环
if (item.children && item.children.length > 0) {
currentRouter.children = that.getList(item.children, currentRouter)
}
// 返回路由数组
return currentRouter
})
},
goPage(){
this.$router.push('/cs1/cs2')
}
}
}
</script>
<style>
</style>
如此即可完成 动态路由添加 可下载文件 运行测试