vue配置文件自動生成路由和菜單實例代碼

寫在前面

每次重復寫路由的時候是不是會覺得很煩,特別是項目大的時候,路由會有特別多,看都看不過來,所以這裡我是有瞭一個router.json的配置文件來對路由做一些簡單的配置,然後讓路由和左側菜單欄可以同時生成。

router.json

主要配置項如下:

{
  "name": "routerConfig",
  "menu": [{
    "id": "1", //路由id,不能重復
    "name": "home",//路由名字
    "path": "/homePage",//路由路徑
    "label": "首頁",//菜單標題
    "selected": true,//默認選中
    "icon": "el-icon-monitor",//菜單顯示圖標
    "open": true,//默認打開
    "component": "homePage/homePage.vue",//組件路由
    "children": [ //子菜單
      {
        "id": "3",
        "name": "getCover",
        "path": "/getCover",
        "label": "封面截取",
        "selected": false,
        "icon": "el-icon-scissors",
        "open": false,
        "component": "getCover/getCover.vue",
        "children": []
      }
    ]
  },{
    "id": "2",
    "name": "testPage",
    "path": "/testPage",
    "label": "測試",
    "selected": false,
    "icon": "el-icon-setting",
    "open": false,
    "component": "test/test.vue",
    "children": []
  },{
    "id": "5",
    "name": "testMenu",
    "path": "/testMenu",
    "label": "菜單測試",
    "selected": false,
    "icon": "el-icon-setting",
    "open": false,
    "component": "testMenu/testMenu.vue",
    "children": []
  }]
}

配置主要分為兩部分,一部分由於菜單生成,一部分用於路由生成,當然兩者也有共用的部分

路由生成

import Vue from 'vue'
import VueRouter from 'vue-router'
import ro from "element-ui/src/locale/lang/ro";
Vue.use(VueRouter)
//引入配置文件router.json
let routerMenu = require('@/config/router.json');
routerMenu = routerMenu.menu;
let menu = [];
//配置路由
let formatRoute = function (routerMenu,menu){
  for(let i = 0; i < routerMenu.length; i++){
    let temp = {
      path: routerMenu[i].path,
      name: routerMenu[i].name,
      //這塊要註意
      //用require這種方式引入的時候,會將你的component分別打包成不同
      //的js,加載的時候也是按需加載,隻用訪問這個路由網址時才會加載
      //這個js
      component: resolve => require([`@/views/${routerMenu[i].component}`], resolve)
    };
    menu.push(temp);
    if(routerMenu[i].children && routerMenu[i].children.length > 0){
    //遞歸生成子菜單的路由
      formatRoute(routerMenu[i].children,menu);
    }
  }
}
//初始化
formatRoute(routerMenu,menu);
//重定向設置
const routes = [
  {
    path: '/',
    redirect: '/homePage'
  },
]
//將生成的路由文件push進去
for(let i = 0; i < menu.length; i++)
  routes.push(menu[i]);
  
const router = new VueRouter({
  routes
})

export default router

菜單生成

<template>
  <div id="leftMenu">

  </div>
</template>

<script>
export default {
  name: "left",
  data(){
    return{
      menu:[]
    }
  },
  methods:{
  //通過路由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{

          }
        }
      }
    },
    //選中菜單節點
    chooseNode(id){
      this.findNodeById(this.menu,id);
      let domTree = this.generatorMenu(this.menu,'',0)
      let leftMenu = document.getElementById('leftMenu');
      leftMenu.innerHTML = domTree;
    },
    //動態生成菜單目錄
    generatorMenu(menu,temp,floor){
      for(let i = 0; i < menu.length; i++){
        temp += `<div style="width: max-content">
                    <div class="menuOption" οnclick="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 = [];
    //獲取路由菜單配置文件
    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>

效果

左側菜單便是自動生成的,點擊菜單欄也會跳轉到對應的路由地址,當然,樣式有點醜,但樣式的話可以自己後續再調整。

這樣的話,我們新加菜單的時候隻需要在配置文件中配置好,就可以直接寫編寫頁面,這樣也給我們省下瞭很多時間。

總結

到此這篇關於vue配置文件自動生成路由和菜單的文章就介紹到這瞭,更多相關vue自動生成路由和菜單內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: