index.ts 1.6 KB
import type { NavigationGuardNext, RouteLocationNormalized, Router, RouteRecordRaw } from "vue-router";

import { createRouter as _createRouter, createWebHistory } from "vue-router";

const routes: RouteRecordRaw[] = [
	{
		path: "/",
		name: "Home",
		component: () => import("@/views/Home.vue"),
		meta: {
			title: "首页",
		},
	},
	{
		path: "/about",
		name: "About",
		component: () => import("@/views/About.vue"),
		meta: {
			title: "关于",
		},
	},
	{
		path: "/user",
		name: "User",
		component: () => import("@/views/User.vue"),
		meta: {
			title: "用户管理",
		},
	},
	{
		path: "/settings",
		name: "Settings",
		component: () => import("@/views/Settings.vue"),
		meta: {
			title: "系统设置",
		},
	},
	{
		path: "/communication",
		name: "Communication",
		component: () => import("@/views/Communication.vue"),
		meta: {
			title: "通信示例",
		},
	},
	{
		path: "/:pathMatch(.*)*",
		name: "NotFound",
		component: () => import("@/views/NotFound.vue"),
	},
];

/**
 * 创建路由实例
 * @param base 路由 base 路径
 */
export function createRouter(base: string = "/"): Router {
	const router = _createRouter({
		history: createWebHistory(base),
		routes,
	});

	// 路由守卫
	router.beforeEach((to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
		// 设置页面标题
		if (to.meta.title) {
			document.title = `${to.meta.title} - Vue3 微应用`;
		}
		next();
	});

	router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
		console.log("[Vue3 微应用] 路由切换:", from.path, "->", to.path);
	});

	return router;
}