使用vue-router中的addRoutes设置权限
2020-07-19 本文已影响0人
Gambler_194b
vue项目中做权限的时候,使用vue-router自带的addRoutes来生成路由是比较好的,具体操作步骤
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router);
// 不需要权限的部分路由
export const defaultRoutes = [{
path: '/login',
name: 'login',
component: () => import('@/view/login.vue')
}];
// 全部路由
const router = new Router({
routes: [
...defaultRoutes
]
});
export default router
// 登录组件
methods: {
login() {
// 开发中这里用请求回来的数据代替,如果请求的数据格式与路有格式不一致,需要解析成路由格式才可以
const list= [
{
path: '/',
name: 'index',
component: 'view/home',
children: [
{
path: '/example-1',
name: 'example1',
meta: {
title: 'title1'
},
component: 'components/example-1'
}, {
path: '/example-2',
name: 'example1',
meta: {
title: 'title2'
},
component: 'components/example-2'
}
]
}
];
this.$store.commit('SET_ROUTES', list);
// 登录之后跳转
this.$router.replace('/');
}
}
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import {setRoutes} from "../router/getRoutes"
Vue.use(Vuex);
export default new Vuex.Store({
state: {
routes: []
},
mutations: {
SET_ROUTES(state, routes) {
setRoutes(routes);
state.routes = routes;
}
}
});
// router/getRoutes.js
import router from "./index";
// 导入默认的配置的静态路由
import { defaultRoutes } from "./index"
export const getRoutes= arr => {
return arr.map(({path, name, component, meta, children}) => {
const route = {
path,
name,
meta: {
...meta,
require: true
},
component: () => import(`@/${component}.vue`)
};
if(children) {
route.redirect = children[0].path;
route.children = getAsyncRoutes(children);
}
return route;
});
};
export const setRoutes = list=> {
const routeList = getAsyncRoutes(list);
router.addRoutes(routeList);
// 路由 options 并不会随着 addRoutes 动态响应,所以要在这里进行设置
router.options.routes = defaultRoutes.concat(routeList);
};
借鉴 (https://blog.csdn.net/FlowGuanEr/article/details/107314253)