DRAFT 路由
约 307 字大约 1 分钟
Vue
2025-10-10
注册
路由器实例是通过 createRouter() 函数创建的,并使用 user() 将其注册为插件。
// src/router.js
import { createMemoryHistory, createRouter } from "vue-router";
const routes = [
// 路由配置
];
const router = createRouter({
history: createMemoryHistory(),
routes,
});
export default router;// src/main.js
import App from "./App.vue";
import { createApp } from "vue";
import router from "@/router/index";
const app = createApp(App);
app.use(router);
app.mount("#app");路由匹配
动态参数
在路由路径中使用
:来定义动态参数。import User from "./User.vue"; // 这些都会传递给 `createRouter` const routes = [ // 动态字段以冒号开始 { path: "/users/:id", component: User }, ];可以在路径参数后添加正则表达式。
在路径参数后面使用
()来定义正则表达式,匹配特定类型的参数。const routes = [ // /:orderId -> 仅匹配数字 { path: "/:orderId(\\d+)" }, // /:productName -> 匹配其他任何内容 { path: "/:productName" }, ];直接在参数后添加量词,匹配参数个数。还可以和括号结合,匹配特定类型的参数个数。
const routes = [ // 匹配 /chapters 和 /chapters/ie92j { path: "/chapters/:chapterId?" }, // /:chapters -> 匹配 /one, /one/two, /one/two/three, 等 { path: "/:chapters+" }, // /:chapters -> 匹配 /, /one, /one/two, /one/two/three, 等 { path: "/:chapters*" }, // 匹配 /1, /1/2, /123/456 等 { path: "/:chapters(\\d+)+" }, // 匹配 /, /1, /1/2, 等 { path: "/:chapters(\\d+)*" }, ];