最近在做一个后台管理项目,涉及到一些菜单权限控制,具体实现如下:(话不多说,直接上代码)
router/index.js
const Home = resolve => require(['@/views/common/Home.vue'], resolve); const AAA = resolve => require(['@/views/page/AAA.vue'], resolve); const BBB = resolve => require(['@/views/pages/BBB.vue'], resolve); const CCC= resolve => require(['@/views/pages/CCC.vue'], resolve); let routes = [{ path: '/', component: Home, name: '首页', redirect: '/AAA', hidden: true, mate: { icon: 'fa fa-home', index: 'AAA' }, children: [{ path: '/AAA', component: AAA, name: '主页' }] }] //从服务器获取路由,进行拼接,所有模块不再以import的形式引入,只能通过require方式加载! export const makeRoute = function (items) { let routes = []; for (var i = 0; i < items.length; i++) { // console.log(items[i]); items[i] = formatRoute(items[i]); if (items[i].children) { //递归处理子路由的component items[i].children = makeRoute(items[i].children); } } return items; } //格式化路由,使component挂载到路由上,生成addRoutes可用的格式 const formatRoute = (item) => { let route = item; route.component = eval(route.component); return route; } export default routes;
main.js(登录成功时,后台返回有权限的路由并存在状态管理器vuex中)
import Vue from 'vue' import App from './App' import VueRouter from 'vue-router' import axios from 'axios' import store from './store' import routes from './router/index' import { makeRoute } from './router' Vue.use(VueRouter) const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { //如果目标路由为登陆时,恢复用户原始状态 if (to.path === '/login') { window.clearInterval(window.interval); store.commit('logOut'); } let allRoutes = store.getters.allRoutes; let loginStatus = store.getters.loginStatus; //登录成功时加载路由及模块 if (from.path === '/login' && allRoutes !== '' && loginStatus) { let routesObj = makeRoute(store.getters.allRoutes); router.addRoutes(routesObj); } //没有登录时自动跳转,开发环境免登陆时注释 if ( to.path !== '/login' && (allRoutes === '' || !loginStatus)) { if(sessionStorage.getItem('userInfo') === null){ next({ path: '/login' }) } else { //刷新当前页面 //重置store参数 let userInfo = JSON.parse(sessionStorage.getItem('userInfo')); store.commit('setUser', userInfo); if(userInfo.routes){ //重新加载路由及模块 let routesObj = makeRoute(userInfo.routes); router.addRoutes(routesObj); } next({path: to.path, query: to.query}); } }else{ //路由的next必须存在,否则无法进入下一页 next(); } })
备注:此方案最大的好处是不用再使用require引入每一个组件并挂载到路由