vue中如何批量引入组件,并注册路由?

76 阅读1分钟

做过vue项目的同学可能都见过类似这样的代码:

import A from '../views/A.vue'
import B from '../views/B.vue'
import C from '../views/C.vue'
routes:[
  {
    path: '/a',
    component: A,
    name: 'A',
  },
  {
    path: '/b',
    component: B,
    name: 'B',
  },
  {
    path: '/c',
    component: C,
    name: 'C',
  },
...
]

项目功能复杂之后,可能数百行类似于这样的代码,有没有办法优化一下呢?

vite提供这样一个方法可批量引入组件;

import.meta.glob; [用法](https://cn.vite.dev/guide/features.html#glob-import)
const componentLabel: Record<string, string> = {
  'animation': '首页',
  'component': '组件',
}
type ModuleType = Record<string, () => Promise<ReturnType<typeof defineComponent>>>
const module: ModuleType = import.meta.glob('../views/**/index.vue');
// 批量创建路由配置
const createRoutes = (modules: ModuleType) => {
  const routes = Object.keys(modules).map((key) => {
    const path = key.replace('../views', '').replace('/index.vue', '');
    const name = path.replace('/', '');
    return {
      path,
      name,
      component: modules[key],
      label: componentLabel[name] || name,
    }
  });
  return routes;
}

export const routes = createRoutes(module);
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    ...routes
  ],
})

这样,再创建新的路由页面就不用再重复写代码了!