在使用vue-router的时候,我们会对路由进行模块化拆分,方便管理维护。
在定义模块路由文件的时候,一般使用export default直接导出路由数组,然后在src/router/index.ts引入模块文件,直接使用扩展运算符...合并各个路由模块。
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import exampleRoutes from './modules/example';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: "Home",
meta: {
title: "首页",
keepAlive: true,
},
component: () => import('@/views/Home/Home.vue'),
},
...exampleRoutes
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
下面介绍export default导出的函数使用typescript约束
1.第一种方式
先使用const定义exampleRoutes,然后再export default exampleRoutes
import { RouteRecordRaw } from 'vue-router'
const exampleRoutes: Array<RouteRecordRaw> = [
{
path: '/example',
name: "Example",
meta: {
title: "案例",
keepAlive: true,
},
component: () => import('@/views/Example/Example.vue'),
},
]
export default exampleRoutes
2.第二种方式
使用as关键字
import { RouteRecordRaw } from 'vue-router'
export default [
{
path: '/example',
name: "Example",
meta: {
title: "案例",
keepAlive: true,
},
component: () => import('@/views/Example/Example.vue'),
},
] as Array<RouteRecordRaw>