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

Some front-end basics (html, css) encountered in practice

1. The div css mouse hand shape is cursor:pointer;...

Vue implements small form validation function

This article example shares the specific code of ...

How to use JSX to implement Carousel components (front-end componentization)

Before we use JSX to build a component system, le...

Detailed tutorial on installing MySQL 5.7.20 on RedHat 6.5/CentOS 6.5

Download the rpm installation package MySQL offic...

Linux operation and maintenance basics httpd static web page tutorial

Table of contents 1. Use the warehouse to create ...

Ant designing vue table to achieve a complete example of scalable columns

Perfect solution to the scalable column problem o...

Introduction to keyword design methods in web design

Many times, we ignore the setting of the web page ...

Vue commonly used high-order functions and comprehensive examples

1. Commonly used high-order functions of arrays S...

Example method of viewing IP in Linux

Knowing the IP address of a device is important w...

Example code for implementing dynamic column filtering in vue+element table

Requirement: When displaying data in a list, ther...

A brief introduction to MySQL InnoDB ReplicaSet

Table of contents 01 Introduction to InnoDB Repli...

Use of VNode in Vue.js

What is VNode There is a VNode class in vue.js, w...