Implementation of obtaining menu function dynamically from the back end using Vue element admin framework

  • 2. Explain in detail
    • 2.1. Add asyncroutes route
    • 2.2. Create a new permission JS file
    • 2.3. Register the permission module in vuex
    • 2.4. Add routing status in Getters
    • 2.5. Modify menu to generate data source
    • 2.6. Get the menu after logging in
    • 2.7. Solve the blank page after refresh
  • 3. Summary

    2. Explain in detail

    The overall idea is: login > get the menu according to the user information after successful login > generate routing information according to the menu

    2.1. Add asyncroutes route

    In Vue router pathsrc\router\index.jsThe asyncroutes array is added to store the routing information corresponding to the menu obtained by the back end.

    export const asyncRoutes = [
      { path: '*', redirect: '/404', hidden: true }

    The difference between constantrotes and asyncroutes

    Constant routes: routes that do not require dynamic judgment permission, such as login page, 404 and other general pages.

    Asyncroutes: a page that needs to dynamically judge permissions and dynamically add them through addroutes

    2.2. Create a new permission JS file

    In vuex pathsrc\store\modules\permission.jsCreate a new permission JS file, which is the most important step. It is mainly to query the menu from the back end and generate a route.

    import { asyncRoutes, constantRoutes } from '@/router'
    import { fetchUserMenuList } from '@/api/user'
    import Layout from '@/layout'
     *Static route lazy loading
     *@ param view format must be XXX / xxx without slash at the beginning
     * @returns 
    export const loadView = (view) => {
      return (resolve) => require([`@/views/${view}.vue`], resolve)
     *Assemble the menu data queried from the back end into data in routing format
     * @param routes
     *@ param Data menu data returned from the backend
    export function generaMenu(routes, data) {
      data.forEach(item => {
        const menu = {
          path: item.url, 
          component: item.component === '#' ? Layout : loadView(item.component), 
          hidden: item. Status = = = 0, // hidden with status 0
          redirect: item.redirect,
          children: [],
          name: item.code,
          meta: item.meta
        if (item.children) {
          generaMenu(menu.children, item.children)
      return routes
    const state = {
      routes: [],
      addRoutes: []
    const mutations = {
      SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        //Splicing static routing and dynamic routing
        state.routes = constantRoutes.concat(routes)
    const actions = {
      generateRoutes({ commit }, token) {
        return new Promise(resolve => {
          //Get the user menu from the back end through the token and add the global status
          fetchUserMenuList(token).then(res => {
            const menuData = Object.assign([],
            const tempAsyncRoutes = Object.assign([], asyncRoutes)
            const accessedRoutes = generaMenu(tempAsyncRoutes, menuData)
            commit('SET_ROUTES', accessedRoutes)
          }).catch(error => {
    export default {
      namespaced: true,

    2.3. Register the permission module in vuex

    If you are using Vue element admin, skip this step because it issrc\store\index.jsAutomatically registered insrc\store\modulesAll modules under. If you use Vue element template, you can refer to admin and index JS file transformation, you can also manually import it.

    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from './getters'
    const modulesFiles = require.context('./modules', true, /\.js$/)
    // you do not need `import app from './modules/app'`
    // it will auto require all vuex module from modules file
    const modules = modulesFiles.keys().reduce((modules, modulePath) => {
      // set './app.js' => 'app'
      const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
      const value = modulesFiles(modulePath)
      modules[moduleName] = value.default
      return modules
    }, {})
    const store = new Vuex.Store({
    export default store

    2.4. Add routing status in Getters

    In vuex pathsrc\store\getters.jsAdd menusroutes status

    menusRoutes: state => state.permission.routes

    2.5. Modify menu to generate data source

    In pathsrc\layout\components\Sidebar\index.vueModify the data source of routes. The original data source is route, which is obtained from vuex instead.

    routes() {
          // return this.$router.options.routes
          return this.$store.getters.menusRoutes

    So far, the logic from obtaining menu data from the back end to page display has been completed. Now start calling after login.

    2.6. Get the menu after logging in

    In vuex pathsrc\store\modules\user.jsIn the login method of, the login is successful, and the routing logic is generated through the token acquisition menu.

    //To get the menu, you must add {root: true} when calling actions in other files
              dispatch('permission/generateRoutes', data, { root: true }).then((accessRoutes) => {

    2.7. Solve the blank page after refresh

    The above contents can realize the function of displaying the menu on the left after logging in, but you will find that the page will become blank every time you refresh the page. This is because when the page is refreshed, the Vue instance will be reloaded, and the data in the vuex store will be re assigned, resulting in the emptying of our routing information in vuex.

    Insrc\permission.jsRe obtaining routing code is added in.

    const accessRoutes = await store.dispatch('permission/generateRoutes', store.getters.token)
              next({, replace: true })

    3. Summary

    So far, the dynamic acquisition of menu content according to user information has been completed.

    This is the end of this article about using Vue element admin framework to dynamically obtain menus from the back end. For more information about Vue element admin dynamically obtaining menu content, please search previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

    Recommended Today

    The difference and relation between Eval (CMD) and eval ($CMD)

    This problem has been bothering me for a long time, and it has finally been solved today Question 1: does Eval need double quotation marks for execution, including: First look at three commands: A:<?php eval(system(dir))?> B:<?php $cmd=”system(dir)”; eval($cmd)?> A result: B result: report errors reflection: It is also a command. Why is there such a […]