准备工作
需要了解的接口
官方提供的路由对象数据类型
RouteRecordRaw
自定义定义路由对象数据类型
// Omit 删除指定类型的key返回删除后的接口类型
export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
name: string;
meta: RouteMeta;
component?: Component | string;
components?: Component;//一个页面或者视图多个路由会使用
children?: AppRouteRecordRaw[];
props?: any;
fullPath?: string;
}
路由目录结构
type 路由对象类型
type.ts
export interface RouteMeta {
title: string;
}
export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
name: string;
meta: RouteMeta;
component?: Component | string;
components?: Component;//一个页面或者视图多个路由会使用
children?: AppRouteRecordRaw[];
props?: any;
fullPath?: string;
}
export type AppRouteModule = AppRouteRecordRaw;
routes/index.ts
import { RouteRecordRaw } from 'vue-router';
// import.meta.globEager 是vite提供的函数可以引入指定目录里面的所有指定类型文件返回数组
const modules = import.meta.globEager('./modules/**/*.ts');
const routeModuleList: RouteRecordRaw[] = [];
Object.keys(modules).forEach((key) => {
const mod = modules[key].default || {};
// console.log('mod :>> ', mod);
const modList = Array.isArray(mod) ? [...mod] : [mod];
routeModuleList.push(...modList);
});
// 处理好数据后统一返回到 路由实例
export const basicRoutes:RouteRecordRaw[] =routeModuleList;
创建路由module
import { AppRouteModule } from "../../types";
const LoginRoute: AppRouteModule = {
path: '/login',
name: 'Login',
component: () => import('/@/views/sys/login/Login.vue'),
meta: {
title: "登录",
},
};
export default LoginRoute;
创建路由实例
import type { App } from 'vue';
import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHashHistory } from 'vue-router';
import { basicRoutes } from './routes';
/**
* 创建路由实例
*/
export const router = createRouter({
history:createWebHashHistory(),
routes:(basicRoutes as unknown) as RouteRecordRaw[]
});
/**
* 路由拦截
*/
router.beforeEach((to,from)=>{
console.log('to :>> ', to,from);
})
/**
* 挂载到vue实例函数
* @param app vue实例
*/
export function setupRouter(app: App<Element>) {
app.use(router);
}
export default router;