vue-admin-element 后台菜单加载 动态路由

修改src/router/index.js文件

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by  (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
 /**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = []  // 没有权限的页面
export const asyncRoutes = []  // 后台加载的菜单 添加 

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router

添加src/store/modules/permission.js文件

import { asyncRoutes, constantRoutes } from '@/router'
import { getMenusIndex } from '@/api/menu'   // 调用后台的接口
import Layout from '@/layout'

/**
 * 格式化菜单 处理后台传过来的菜单格式
 * @param {*} routes 
 * @param {*} data 
 */
export function formatMenus(routes, data) {
    data.forEach(item => {
        const menu = {}
        if(item.top){// 一级菜单
            menu.path = item.path;
            menu.component = Layout
            menu.children = []
            menu.alwaysShow = true
            menu.redirect = 'noRedirect'
            menu.name = item.name
            menu.meta = { title: item.meta.title, icon: item.meta.icon }
        }else{
            // 二级菜单
            menu.path = item.path
            menu.component =  resolve => require([`@/views/${item.name}/index`], resolve)
            menu.children = []
            menu.name = item.name
            menu.meta = { title: item.meta.title, icon: item.meta.icon }
        }
        if (item.children) {
            formatMenus(menu.children, item.children)
        }
        routes.push(menu)
    })
}


const state = {
    routes: [],
}
const mutations = {
    SET_ROUTES: (state, routes) => {
        state.routes = constantRoutes.concat(routes)
    }
}
const actions = {
    generateRoutes({ commit }) {
        return new Promise(resolve => {
            const loadMenuData = []
            // 获取后台菜单接口
            getMenusIndex().then(response => {
                let data = response.data
                Object.assign(loadMenuData, data)
                // 格式化菜单
                formatMenus(asyncRoutes, loadMenuData)
                let accessedRoutes
                accessedRoutes = asyncRoutes
                commit('SET_ROUTES', accessedRoutes)
                resolve(accessedRoutes)
            }).catch(error => {
                console.log(error)
            })
        })
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}

修改src/store/getters.js文件

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
  routers: state => state.permission.routes   // 异步加载的路由  添加
}
export default getters

修改src/store/index.js文件

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import permission from './modules/permission'   // 导入permission文件 添加

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    settings,
    user,
    permission   // 添加
  },
  getters
})

export default store

修改src/permission.js文件

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          // 获取异步加载的路由  添加
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          // 添加到路由中  添加
          router.addRoutes(accessRoutes)

          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

修改src/layout/components/Sidebar/index.vue文件

<template>
  <div :class="{'has-logo':showLogo}">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="false"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
      >
        <sidebar-item v-for="route in routers" :key="route.path" :item="route" :base-path="route.path" />
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/styles/variables.scss'

export default {
  components: { SidebarItem, Logo },
  computed: {
    ...mapGetters([
      'sidebar',
      'routers'  // 名称对应src/store/getters.js 中添加的名称 添加  
      /*   修改  routes 为 routers */
    ]),
    activeMenu() {
      const route = this.$route
      const { meta, path } = route
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu
      }
      return path
    },
    showLogo() {
      return this.$store.state.settings.sidebarLogo
    },
    variables() {
      return variables
    },
    isCollapse() {
      return !this.sidebar.opened
    }
  }
}
</script>

注意:


踩坑:eslint Cannot read property ‘range’ of null错误
处理:babel-eslint 版本为8.0.1 src/permission.js devDependencies中

"babel-eslint": "8.0.1",

感谢https://www.cnblogs.com/ryans/p/8411298.html

后台接口返回格式:


vue-admin-element 后台菜单加载 动态路由_第1张图片
项目地址: https://github.com/evolutionary-boy/project-vote-admin

你可能感兴趣的:(vue)