vue-router動態註冊

來源

寫路由時每新建一個路由都需要import一下或其他方式(如箭頭函數import)很是麻煩,有麻煩就有需求,於是以下這篇文章就來了

吹水

要想動態註冊路由,那麼就需要制定規則,即每個路由有一定的規則,來實現動態註冊,我的路由文件是放在views下,其中每個vue文件有一個對應的包名

藉助vue官網中基礎組件的自動化全局註冊

vue走你

webpake走你

代碼中不難看出歸功於webpack的require.context使我們可以獲取到文件夾下面的文件,關鍵點在(files(item).default)獲取(不知道怎麼取名,望大佬分享下)
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home/Home.vue'
import Login from '../views/login/Login.vue'
Vue.use(VueRouter)

//獲取文件,自動掛載在router下
const files = require.context(
  // 其組件目錄的相對路徑
  '../views',
  // 是否查詢其子目錄
  true,
  // 匹配基礎組件文件名的正則表達式
  /\.vue/
)
let items = [{
  path: "",
  redirect: "/MenuSystem"
}];

files.keys().forEach(item => {
  let name = item.split('/')[2].replace('.vue', "");
  items.push({
    path: `/${name}`,
    component: files(item).default
  })
})

const routes = [
  {
    path: '/Login',
    component: Login
  },
  {
    path: '/',
    component: Home,
    children: [...items]
    // children: [{
    //   path: "",
    //   redirect: "/MenuSystem"
    // }, {
    //   path: "/MenuSystem",
    //   component: MenuSystem
    // }, {
    //   path: "/RoleSystem",
    //   component: RoleSystem
    // }, {
    //   path: "/ActionSystem",
    //   component: ActionSystem
    // }, {
    //   path: "/SystemAuthority",
    //   component: SystemAuthority
    // }, {
    //   path: "/MenuAuthority",
    //   component: MenuAuthority
    // }, {
    //   path: "/PostInfo",
    //   component: PostInfo
    // }
    // ]
  }, {
    path: "*",
    redirect: "/"
  }
]
// 解決菜單跳轉相同路徑下報錯
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

export default router

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章