vue-router悄然發佈了5.0版本,根據官方說法,V5 是一個過渡版本,它將unplugin-vue-router(基於檔案的路由)合併到了核心包中。這意味著V5版本直接支持基於檔案自動生成路由,無需再引入unplugin-vue-router。
這一變化標誌著前端開發模式的一個重要轉折點。過去,開發者需要手動定義路由配置,雖然這種方式靈活,但隨著項目規模增大,維護成本也隨之增加。現在,Vue Router 5.0內建了基於檔案的路由系統,使得路由管理變得更加直觀和高效。
在傳統的Vue Router使用方式中,我們需要手動創建路由:
import { createRouter, createWebHistory } from "vue-router";
import Home from "./views/Home.vue";
import About from "./views/About.vue";
const routes = [
{
path: "/",
name: "home",
component: Home,
},
{
path: "/about",
name: "about",
component: About,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
而基於檔案的路由系統允許我們通過目錄結構自動生成路由,例如:
src/
├── pages/
│ ├── index.vue # -> /
│ ├── about.vue # -> /about
│ ├── user/
│ │ └── index.vue # -> /user
│ └── user-[id].vue # -> /user/:id
無需手動創建,直接導入即可:
import { routes } from "vue-router/auto-routes";
const router = createRouter({
history: createWebHistory(),
routes,
});
省去了手動定義路由的繁瑣步驟。
router.push(xxx)現在會有提示了meta等額外數據必須在.vue檔案使用definePage或route標籤聲明,點此查看教程安裝
pnpm add vue-router@5
vite.config.ts
import VueRouter from "vue-router/vite";
export default defineConfig({
plugins: [
VueRouter({
dts: "typed-router.d.ts",
}),
// ⚠️ Vue 必須放在 VueRouter() 之後
Vue(),
],
});
tsconfig.json
// tsconfig.json
{
"include": ["typed-router.d.ts"],
"vueCompilerOptions": {
"plugins": [
"vue-router/volar/sfc-typed-router",
"vue-router/volar/sfc-route-blocks"
]
}
}
src/router/index.ts
import { createRouter, createWebHistory } from "vue-router";
import { routes, handleHotUpdate } from "vue-router/auto-routes";
export const router = createRouter({
history: createWebHistory(),
routes,
});
// 這將在不重新加載頁面的情況下運行時更新路由
if (import.meta.hot) {
handleHotUpdate(router);
}
根據官方文檔,基於檔案的路由系統有以下具體規則:
索引路由:任何 index.vue 檔案(必須全小寫)將生成空路徑,類似於 index.html 檔案:
src/pages/index.vue 生成 / 路由src/pages/users/index.vue 生成 /users 路由嵌套路由:當在同一層級同時存在同名資料夾和 .vue 檔案時,會自動生成嵌套路由。例如:
src/pages/
├── users/
│ └── index.vue
└── users.vue
這將生成如下路由配置:
const routes = [
{
path: "/users",
component: () => import("src/pages/users.vue"),
children: [
{ path: "", component: () => import("src/pages/users/index.vue") },
],
},
];
不帶佈局嵌套的路由:有時你可能想在URL中添加斜線形式的嵌套,但不想影響UI層次結構。可以使用點號(.)分隔符:
src/pages/
├── users/
│ ├── [id].vue
│ └── index.vue
└── users.vue
要添加 /users/create 路由而不將其嵌套在 users.vue 元件內,可以創建 src/pages/users.create.vue 檔案,. 會被轉換為 /:
const routes = [
{
path: "/users",
component: () => import("src/pages/users.vue"),
children: [
{ path: "", component: () => import("src/pages/users/index.vue") },
{ path: ":id", component: () => import("src/pages/users/[id].vue") },
],
},
{
path: "/users/create",
component: () => import("src/pages/users.create.vue"),
},
];
路由組:有時需要組織檔案結構而不改變URL。路由組允許你邏輯性地組織路由,而不影響實際URL:
src/pages/
├── (admin)/
│ ├── dashboard.vue
│ └── settings.vue
└── (user)/
├── profile.vue
└── order.vue
生成的URL:
/dashboard -> 渲染 src/pages/(admin)/dashboard.vue/settings -> 渲染 src/pages/(admin)/settings.vue/profile -> 渲染 src/pages/(user)/profile.vue/order -> 渲染 src/pages/(user)/order.vue命名視圖:可以通過在檔名後附加 @ + 名稱來定義命名視圖,如 src/pages/[email protected] 將生成:
{
path: '/',
component: {
aux: () => import('src/pages/[email protected]')
}
}
默認情況下,未命名的路由被視為 default,即使有其他命名視圖也不需要將檔案命名為 [email protected]。
動態路由:使用方括號語法定義動態參數:
[id].vue -> /users/:id[category]-details.vue -> /electronics-details[...all].vue -> 通配符路由 /all/*這一變化將顯著改變Vue應用的開發流程:
對於現有項目,Vue Router 5.0提供了平滑的遷移路徑:
Vue Router 5.0的基於檔案路由系統提供了豐富的配置選項,可以根據項目需求進行定制:
自定義路由目錄:默認情況下,系統會在 src/pages 目錄中查找 .vue 檔案,但可以通過配置更改此行為。
命名路由:所有生成的路由都會自動獲得名稱屬性,避免意外將使用者引導至父路由。默認情況下,名稱使用檔路徑生成,但可以通過自定義 getRouteName() 函數覆蓋此行為。
類型安全:系統會自動生成類型聲明檔案(如 typed-router.d.ts),提供幾乎無處不在的 TypeScript 驗證。
配置示例:
// vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import VueRouter from "unplugin-vue-router/vite";
export default defineConfig({
plugins: [
VueRouter({
routesFolder: "src/pages", // 自定義路由目錄
extensions: [".vue"], // 指定路由檔案擴展名
dts: "typed-router.d.ts", // 生成類型聲明檔案
importMode: (filename) => "async", // 自定義導入模式
}),
vue(),
],
});
在實際項目中採用基於檔案的路由時,建議遵循以下最佳實踐:
Vue Router 5.0引入的基於檔案的路由系統代表了前端開發模式的重要演進。它將 Nuxt.js 等框架成功的路由理念整合到了 Vue 的核心生態中,使開發者能夠以更簡潔、更直觀的方式管理應用路由。
這一變化不僅減少了樣板代碼,提高了開發效率,還促進了更一致的項目結構。隨著更多開發者採用這一新模式,我們可以期待看到更高質量、更易維護的 Vue 應用程式出現,這將為整個前端社群帶來積極的影響。