Association processing of dynamic menu and routing in Vue element front-end application development

Time:2021-11-29
catalogue
  • summary
  • 1. Menu and routing processing
  • 2. Menu and routing list
  • 3. Login process processing

summary

In many systems I develop, including WinForm hybrid framework, bootstrap development framework and other series of products, I tend to dynamically configure menus, manage menu permissions and page permissions of corresponding roles, and realize the system’s control over user permissions. Menus generally include name, icon, sequence, URL connection and other related information. For Vue + element front-end applications, It should be similar in principle. This essay introduces how to maintain and display the dynamic menu by combining the dynamic menu configuration of the server and the association processing of local routing.

1. Menu and routing processing

The Vue front-end also needs to introduce the concept of routing. Routing is the set of corresponding paths that can be accessed by our front-end. Routing defines a lot of complex information that is not available in the conventional menu, but we can’t modify them at will. Therefore, our approach is based on the locally configured routing list, and the menu is configured in the backing mode, The front end dynamically obtains the menu list through the interface. Through the corresponding relationship between the menu name and the route name, we take the menu set as the comparison, then filter the list of all local static routes, then obtain the route list that users can access, and set the dynamic route to the front end, so as to realize the interface according to different user roles / permissions, The user’s menu interface and accessible routing set are changed.

The general operation process of menu routing processing is as follows

The concepts of dynamic menu, local route, menu navigation and accessible route of the front-end interface are as follows.

In front-end interface processing, we display dynamic menu information through element interface components, and realize the process of menu jump to the corresponding view in combination with the relationship between menu and routing.

2. Menu and routing list

According to the previous introduction, we defined some dynamic menu information returned from the server. These menu information is a collection of JSON objects, as shown in the following interface.

[
  {
    id: '1',
    pid: '-1',
    Text: 'home page',
    icon: 'dashboard',
    name: 'dashboard'
  },
  {
    id: '2',
    pid: '-1',
    Text: 'product list',
    icon: 'table',
    name: 'product'
  },
  {
    id: '3',
    pid: '-1',
    Text: 'first level menu',
    icon: 'example',
    children: [
      {
        id: '3-1',
        pid: '3',
        Text: 'secondary menu 1',
        name: 'icon',
        icon: 'example'
      },
      {
        id: '3-2',
        pid: '3',
        Text: 'secondary menu 2',
        icon: 'tree',
        children: [
          {
            id: '3-2-1',
            pid: '3-2',
            Text: 'three level menu 1',
            name: 'form',
            icon: 'form'
          },
          {
            id: '3-2-2',
            pid: '3-2',
            Text: 'three level menu 2',
            name: 'menu1-1',
            icon: 'form'
          },
          {
            id: '3-2-3',
            pid: '3-2',
            Text: 'three level menu 3',
            name: 'menu1-2',
            icon: 'form'
          },
          {
            id: '3-2-4',
            pid: '3-2',
            Text: 'three level menu 4',
            name: 'menu1-3',
            icon: 'form'
          }
        ]
      }
    ]
  },
  {
    id: '99',
    pid: '-1',
    Text: 'company official website',
    icon: 'table',
    name: 'external-link'
  }
]

The JSON of the menu is obtained dynamically according to the role. Different roles correspond to different menu sets. The menu is a multi-level tree list, which can define an infinite multi-level display. The JSON format view is as follows.

The Vue front-end needs to initialize all routes defining the front-end page, including the layout and other information of the routing page.

We can define all the routing information corresponding to the front end in a JS file, as shown below

//Define all routes of the system, and the specific route presentation is filtered by menu data
export const asyncRoutes = {
  'dashboard': {
    path: '/dashboard',
    component: Layout,
    children: [{
      path: 'dashboard',
      name: 'dashboard',
      component: () => import('@/views/dashboard/index')
    }]
  },
  'product': {
    path: '/product',
    component: Layout,
    children: [{
      path: '/product',
      name: 'product',
      component: () => import('@/views/Product/index')
    }]
  },

  ............................... // omitted part

  'icon': {
    path: '/icon',
    component: Layout,
    children: [{
      path: '/icon',
      name: 'icon',
      component: () => import('@/views/icons/index')
    }]
  },

  'external-link': {
    path: 'http://www.iqidi.com',
    name: 'external-link'
  }
}

The route here does not need to be nested, because the nested relationship needs to be defined for menu display.

In addition, since the system needs to run normally before logging in to request the back-end dynamic menu, we need to preset some basic routing information, such as login interface, redirect page, home page link and so on. Therefore, we can separate two routing objects to manage these information separately.

For route management, we need to create routes by default, reset routes, and dynamically set new routes. We encapsulate several functions to handle these operations.

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

const router = createRouter()

//Reset route
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

After processing in the login interface, the user will obtain the dynamic routing information through the corresponding action (note that here, first obtain the dynamic menu, and then filter the local route, that is, the dynamic routing information). After obtaining the dynamic route, set the route set that can be accessed by the front end, as shown in the following code.

With these new routes, the menu of the front-end system can work normally. Otherwise, even if the menu is displayed on the interface, you can’t access a specific view page and jump to page 404 because there is no route.

3. Login process processing

The process of routing was briefly introduced earlier. In fact, we should start with the login interface.

Take the login interface as an example. After the user logs in, the user’s account and password need to be verified first. After success, continue to request the corresponding dynamic menu set of the user, and switch to the corresponding page or home page through routing.

In the store / modules / user.js module, the corresponding login processing action is defined, as shown below

We ignore the process of user login verification and token processing, and mainly focus on the process of dynamic menu request and routing.

In the processing before the arrival of the intercepted route, we define the corresponding route information request logic, as shown below.


router.beforeEach(async(to, from, next) => {

In the corresponding module for menu routing, we define a state to carry these important information, as shown in the following definition of state.


const state = {
  menuItems: [],
  routes: [],
  addRoutes: [],
  asyncRoutes: asyncRoutes
}
//Mutation with routing and menu defined
const mutations = {
  SET_ROUTES: (state, routes) => {
    // var list = convertRoute(routes)
    Routes. Push ({path: '*', redirect: '/ 404', hidden: true}) // this is the default error route

    state.addRoutes = routes
    state.routes = [].concat(routes)// constantRoutes.concat(routes)
  },
  SET_MENUS: (state, menus) => {
    state.menuItems = menus
  }
}
//Defines the action processing for generating dynamic routes
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      getMenus().then(res => {
        Const menu = res.data | [] // obtain menu information uniformly through the interface
        const routes = []

        menus.forEach(item => {
          filterRoutes(routes, item)
        })
        Console.log (routes) // print routes

        commit('SET_ROUTES', routes)
        commit('SET_MENUS', menus)
        resolve(routes)
      });
    })
  }
}

Finally, return the corresponding JS definition module class information.


export default {
  namespaced: true,
  state,
  mutations,
  actions
}

In front-end interface processing, we display dynamic menu information through element interface components, and realize the process of menu jump to the corresponding view in combination with the relationship between menu and routing.

Let’s take a look at the dynamic menu effect generated by the interface.

Due to the cooperation of dynamic menu display and dynamic routing, it can not only display the dynamic menu at the front end, but also refresh the accessible route according to the menu set. The combination of the two can successfully open the corresponding view page.

To review again, the general operation process of menu routing processing is as follows

The above is the detailed content of the association processing of dynamic menus and routes in the front-end application development of Vue element. For more information about dynamic menus and routes of Vue element, please pay attention to other relevant articles of developpaer!

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]