vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vite动态导入vue路由配置

如何用vite动态导入vue的路由配置详解

作者:星极天下第一

这篇文章主要介绍了如何用vite动态导入vue的路由配置的相关资料,动态导入路由模仿了uniapp的页面配置文件结构,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

在Vue应用中,通过路由可以实现不同页面之间的切换,同时也可以实现页面之间的传参和控制页面的显示与隐藏。但是我们在开发的过程中,会发现在路由配置中的路由配置和我们的项目结构高度重复,在我们修改页面文件结构时非常的麻烦与复杂,这时候,如果可以动态的导入路由,就可以大大提示我们项目的可维护性。

我们在开发中会经常听见一句话,约定大于配置,路由的动态导入也是这句话应用的一种,我们这里动态导入路由模仿了在uniapp进行小程序开发的页面配置文件,要求有以下几点:

结构展示如下:

page.ts文件展示:

//home的page.ts
export default {
  title: '首页',
  menuOrder: 1,
  childrens: [
    `../pages/homechildren`
  ]
}
//homechildren的page.ts
export default {
  title: '首页的子组件',
  menuOrder: 1,
  isChild: true,
}
//login的page.ts
export default {
  title: '登录',
  menuOrder: 2
}

此时我们要通过vite的函数import.meta.glob()和import()扫描pages文件夹动态生成路由,代码如下:

//路由配置文件
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const pages = import.meta.glob('../pages/**/page.ts', {
  eager: true,
  import: 'default'
})

const components = import.meta.glob('../pages/**/index.vue')

const getChildRoutes = async (childrens: string[]) => {
  const res = [];

  for (const item of childrens) {
    const pageModule = await import(`${item}/page.ts`);
    const componentModule = await import(`${item}/index.vue`);

    const routePath = item.replace('../pages/', '').replace('/page.ts', '') || '/';
    const name = routePath.split('/').filter(Boolean).join('-') || 'index';

    res.push({
      path: routePath,
      name,
      component: componentModule.default,
      meta: pageModule.default
    });
  }

  return res;
};

const routes = Object.entries(pages).filter(([path, meta]: [string, any]) => !meta.isChild).map(([path, meta]: [string, any]) => {
  const compPath = path.replace('page.ts', 'index.vue')
  path = path.replace('../pages', '').replace('/page.ts', '') || '/';
  const name = path.split('/').filter(Boolean).join('-') || 'index';

  return {
    path,
    name,
    component: components[compPath],
    meta: meta,
    children: !!meta.childrens ? getChildRoutes(meta.childrens) : []
  } as RouteRecordRaw
})

const router = createRouter({
  history: createWebHistory(),
  routes: routes,
})

//路由重定向
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    next('/home')
  } else if (!routes.some(route => route.path === to.path)) {
    next('/home')
  } else {
    next()
  }
  
})

export {
  router
}

效果展示:

路由对象展示:

总结 

到此这篇关于如何用vite动态导入vue的路由配置的文章就介绍到这了,更多相关vite动态导入vue路由配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文