The vue configuration file automatically generates routing and menu instance code

The vue configuration file automatically generates routing and menu instance code

Written in front

Do you feel annoyed every time you write routes repeatedly? Especially when the project is large, there will be so many routes that you can't even keep track of them. So here I have a router.json configuration file to do some simple configuration of the routes, and then the routes and the left menu bar can be generated at the same time.

router.json

The main configuration items are as follows:

{
  "name": "routerConfig",
  "menu": [{
    "id": "1", //Route id, cannot be repeated"name": "home", //Route name"path": "/homePage", //Route path"label": "Home", //Menu title"selected": true, //Selected by default"icon": "el-icon-monitor", //Menu display icon"open": true, //Open by default"component": "homePage/homePage.vue", //Component route"children": [ //Submenu {
        "id": "3",
        "name": "getCover",
        "path": "/getCover",
        "label": "Cover capture",
        "selected": false,
        "icon": "el-icon-scissors",
        "open": false,
        "component": "getCover/getCover.vue",
        "children": []
      }
    ]
  },{
    "id": "2",
    "name": "testPage",
    "path": "/testPage",
    "label": "Test",
    "selected": false,
    "icon": "el-icon-setting",
    "open": false,
    "component": "test/test.vue",
    "children": []
  },{
    "id": "5",
    "name": "testMenu",
    "path": "/testMenu",
    "label": "Menu Test",
    "selected": false,
    "icon": "el-icon-setting",
    "open": false,
    "component": "testMenu/testMenu.vue",
    "children": []
  }]
}

The configuration is mainly divided into two parts, one for menu generation and the other for route generation. Of course, there are also common parts between the two.

Route Generation

import Vue from 'vue'
import VueRouter from 'vue-router'
import ro from "element-ui/src/locale/lang/ro";
Vue.use(VueRouter)
//Introduce the configuration file router.json
let routerMenu = require('@/config/router.json');
routerMenu = routerMenu.menu;
let menu = [];
//Configure routing let formatRoute = function (routerMenu,menu){
  for(let i = 0; i < routerMenu.length; i++){
    let temp = {
      path: routerMenu[i].path,
      name: routerMenu[i].name,
      //Note that when you use require to import your components, they will be packaged into different js files. They will be loaded on demand. This js file will only be loaded when you access the route URL.
      component: resolve => require([`@/views/${routerMenu[i].component}`], resolve)
    };
    menu.push(temp);
    if (routerMenu[i].children && routerMenu[i].children.length > 0) {
    //Recursively generate submenu routes formatRoute(routerMenu[i].children,menu);
    }
  }
}
//Initialize formatRoute(routerMenu,menu);
//Redirection settings const routes = [
  {
    path: '/',
    redirect: '/homePage'
  },
]
//Push the generated routing file in for(let i = 0; i < menu.length; i++)
  routes.push(menu[i]);
  
const router = new VueRouter({
  routes
})

export default router

Menu Generation

<template>
  <div id="leftMenu">

  </div>
</template>

<script>
export default {
  name: "left",
  data(){
    return {
      menu:[]
    }
  },
  methods:{
  //Find the node by routing id findNodeById(node,id){
      for(let i = 0; i < node.length; i++){
        if(id == node[i].id){
          node[i].selected = true;
          if(node[i].children && node[i].children.length > 0){
            this.findNodeById(node[i].children,id);
          }
          node[i].open = !node[i].open;
          if(this.$route.path !== node[i].path) this.$router.push(node[i].path);
        }else{
          node[i].selected = false;
          if(node[i].children && node[i].children.length > 0){
            this.findNodeById(node[i].children,id);
          }else{

          }
        }
      }
    },
    //Select the menu node chooseNode(id){
      this.findNodeById(this.menu,id);
      let domTree = this.generatorMenu(this.menu,'',0)
      let leftMenu = document.getElementById('leftMenu');
      leftMenu.innerHTML = domTree;
    },
    //Dynamically generate menu directory generatorMenu(menu,temp,floor){
      for(let i = 0; i < menu.length; i++){
        temp += `<div style="width: max-content">
                    <div class="menuOption" onclick="chooseNode(${menu[i].id})"
                            style="text-indent: ${floor}em;
                            background-color: ${menu[i].selected?'aquamarine':''};
                            cursor: pointer;
                            margin-top: 0.3rem;>
                        <i class="${menu[i].icon}"></i>
                        ${menu[i].label}`
        if(!menu[i].open && menu[i].children && menu[i].children.length > 0){
          temp += `<i style="margin-left: 1rem" class="el-icon-arrow-down"></i>`
        }else{
          if(menu[i].open && menu[i].children && menu[i].children.length > 0){
            temp += `<i style="margin-left: 1rem" class="el-icon-arrow-up"></i>`
          }
        }
        temp += `</div>`
        if(menu[i].open && menu[i].children && menu[i].children.length != 0){
          temp = this.generatorMenu(menu[i].children,temp,floor+1);
        }
        temp += `</div>`
      }
      return temp;
    }
  },
  created() {

  },
  mounted() {
    window.chooseNode = this.chooseNode;
    let menu = [];
    //Get the routing menu configuration file const router = require('@/config/router.json');
    menu = router.menu;
    this.menu = menu;
    let domTree = this.generatorMenu(menu,'',0)
    let leftMenu = document.getElementById('leftMenu');
    leftMenu.innerHTML = domTree;
  }
}
</script>

<style scoped>
  #leftMenu{
    min-height: calc(100vh - 44px - 1rem);
    background-color: cornflowerblue;
    text-align: left;
    padding: 0.5rem 1rem;
    font-size: large;
    font-weight: bold;
  }
  .selectedM{
    background-color: aquamarine;
  }
  .menuOption{
    cursor: pointer;
  }
</style>

Effect

The menu on the left is automatically generated. Clicking the menu bar will jump to the corresponding routing address. Of course, the style is a bit ugly, but you can adjust the style yourself later.

In this way, when we add a new menu, we only need to configure it in the configuration file, and we can directly write the page, which also saves us a lot of time.

Summarize

This is the end of this article about automatically generating routes and menus from vue configuration files. For more relevant content about automatically generating routes and menus from vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue dynamic addition of routing and generation of menu method example

<<:  MySQL 8.0.18 adds users to the database and grants permissions

>>:  MySQL database implements MMM high availability cluster architecture

Recommend

Media query combined with rem layout in CSS3 to adapt to mobile screens

CSS3 syntax: (1rem = 100px for a 750px design) @m...

Introduction to scheduled tasks in Linux system

Table of contents 1. Customize plan tasks 2. Sync...

How to deploy zabbix_agent in docker

zabbix_agent deployment: Recommendation: zabbix_a...

Detailed explanation of Vue's simple store

The simplest application of store in Vue is globa...

Installation tutorial of MySQL 5.7.17 zip package version under win10

The installation tutorial of mysql5.7.17 is share...

How to enable Swoole Loader extension on Linux system virtual host

Special note: Only the Swoole extension is instal...

Why can't I see the access interface for Docker Tomcat?

Question: Is the origin server unable to find a r...

JavaScript implements simple calculator function

This article example shares the specific code of ...

Complete steps for vue dynamic binding icons

0 Differences between icons and images Icons are ...

abbr mark and acronym mark

The <abbr> and <acronym> tags represen...

Web page CSS priority is explained in detail for you

Before talking about CSS priority, we need to und...

MySQL 5.7.18 MSI Installation Graphics Tutorial

This article shares the MySQL 5.7.18 MSI installa...

How to install the latest version of docker using deepin apt command

Step 1: Add Ubuntu source Switch to root su root ...