router.js 1.58 KB
/*
 * @Date: 2022-05-26 13:57:28
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2022-06-15 11:00:05
 * @FilePath: /tswj/src/router.js
 * @Description: 文件描述
 */
import { createRouter, createWebHashHistory } from 'vue-router';
import RootRoute from './route.js';
import { generateRoute } from './utils/generateRoute'

// TAG: 路由配置表
/**
 * 把项目独有的路由配置到相应的路径,默认路由文件只放公用部分
 * 但是 vue 文件内容还是要事先准备好
 */
const modules = import.meta.globEager('@/router/routes/modules/**/*.js'); // Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块
const routeModuleList = [];

Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

// 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里

const router = createRouter({
  history: createWebHashHistory('/index.html'),
  routes: [...RootRoute, ...routeModuleList]
});

// TAG: 动态生成路由
/**
 * generateRoute 负责把后台返回数据拼接成项目需要的路由结构,动态添加到路由表里面
 */
router.beforeEach((to) => { // next 不能用了,被return替代了
  if (!router.hasRoute(to.name)) { // 如果不存在
    router.addRoute(generateRoute(to)) // 新增路由
    // 触发重定向
    return to.fullPath
  }
})

router.afterEach(() => {
  // console.warn(to);
  // console.warn(wx);
  // share(to)
})

export default router;