文章

動態路由與路由參數

在 Vue Router 中,動態路由允許我們為 URL 路徑中的部分設置參數,並根據這些參數來渲染對應的組件。這在構建用戶詳細頁面、文章詳情頁面等需要通過不同 ID 來顯示不同內容的場景中特別有用。

1. 動態路由的基本概念

動態路由允許我們設置帶有參數的路由,例如 /user/:id,其中 :id 是一個路由參數,表示該部分的內容是動態的,可以根據不同的 URL 進行匹配和傳遞。

2. 動態路由的基本使用

1. 定義動態路由

在路由配置中,動態部分使用 : 來定義。以下是一個基礎的動態路由範例:

1
2
3
4
5
import UserComponent from './components/UserComponent.vue';

const routes = [
  { path: '/user/:id', component: UserComponent },
];

在這裡,當路徑是 /user/1/user/2 這樣的 URL 時,UserComponent 都會被加載並顯示。

2. 獲取路由參數

在對應的 Vue 組件中,我們可以通過 this.$route.params 訪問動態路由的參數。比如,如果我們定義了一個動態路由 /user/:id,那麼在組件中可以這樣獲取參數:

1
2
3
4
5
export default {
  mounted() {
    console.log(this.$route.params.id); // 獲取動態路由中的 id
  },
};

範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
  <div>
    <h1>用戶頁面</h1>
    <p>用戶 ID: </p>
  </div>
</template>

<script>
export default {
  computed: {
    userId() {
      return this.$route.params.id; // 獲取動態路由中的 id
    },
  },
};
</script>

當用戶訪問 /user/1 時,頁面會顯示 “用戶 ID: 1”。如果訪問 /user/2,則會顯示 “用戶 ID: 2”。

3. 嵌套路由與動態路由參數

動態路由也可以和嵌套路由結合使用。例如,我們希望在 /user/:id/profile/user/:id/posts 中加載不同的內容,這時可以使用嵌套路由。

定義嵌套路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const routes = [
  {
    path: '/user/:id',
    component: UserComponent,
    children: [
      {
        path: 'profile',
        component: UserProfile,
      },
      {
        path: 'posts',
        component: UserPosts,
      },
    ],
  },
];

這樣,當用戶訪問 /user/1/profile 時,UserProfile 組件會被加載,而訪問 /user/1/posts 時,會加載 UserPosts 組件。

獲取嵌套路由的參數

即使是嵌套路由,子路由中的組件同樣可以通過 this.$route.params 訪問父路由中的參數。

1
2
3
4
5
export default {
  mounted() {
    console.log(this.$route.params.id); // 獲取父路由的 id
  },
};

4. 動態路由中的多個參數

有時我們可能需要在路由中包含多個參數。這時只需要在路由配置中添加多個 : 前綴的參數即可。

定義多個參數

1
2
3
const routes = [
  { path: '/user/:id/post/:postId', component: UserPostComponent },
];

這樣的路徑 /user/1/post/101 會匹配到 UserPostComponent,並且可以在組件中獲取到兩個參數:

1
2
3
4
5
6
export default {
  mounted() {
    console.log(this.$route.params.id); // 用戶 ID
    console.log(this.$route.params.postId); // 帖子 ID
  },
};

5. 命名路由與參數

除了使用路徑參數,我們還可以使用 命名路由 來導航,這樣更靈活和可維護。命名路由允許我們通過名稱來導航,並將參數作為對象傳遞。

定義命名路由

1
2
3
const routes = [
  { path: '/user/:id', component: UserComponent, name: 'user' },
];

使用命名路由導航

1
this.$router.push({ name: 'user', params: { id: 123 } });

這樣會導航到 /user/123,並自動解析 id 參數。

6. 動態路由的匹配規則

Vue Router 提供了靈活的路由匹配規則。例如:

  • *:匹配所有路徑。
  • :id(\\d+):自定義正則表達式來匹配參數,這樣可以限制 id 必須是數字。

使用正則匹配

1
2
3
const routes = [
  { path: '/user/:id(\\d+)', component: UserComponent }, // 只能匹配數字的 id
];

這樣的路由只會匹配 /user/123,但不會匹配 /user/abc

7. 重定向和別名

  • 重定向:可以將一個路由重定向到另一個路徑,並且動態參數會自動傳遞。
1
2
3
const routes = [
  { path: '/old-path/:id', redirect: '/new-path/:id' },
];
  • 別名:別名可以讓同一個路徑有多個不同的訪問方式。
1
2
3
const routes = [
  { path: '/user/:id', component: UserComponent, alias: '/member/:id' },
];

這樣 /user/123/member/123 都會匹配到同一個組件。

8. 處理無效的動態路由

如果用戶訪問了一個不存在的路由,我們可以通過設置「404」頁面來捕獲無效的路由:

1
2
3
const routes = [
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFoundComponent },
];

這樣當用戶訪問不存在的路徑時,會渲染 NotFoundComponent

總結

  • 動態路由允許我們定義帶有參數的路由,可以根據 URL 的不同部分來顯示對應的內容。
  • 可以通過 this.$route.params 獲取路由中的參數,並將其應用於組件的渲染和邏輯。
  • Vue Router 支持多個參數、嵌套路由,以及通過命名路由進行參數傳遞。
  • 動態路由配合正則表達式、重定向和別名,可以構建更靈活的導航系統。

動態路由讓應用的路由配置更加靈活,也能讓開發者在單頁應用中處理更加複雜的導航需求。

本文章以 CC BY 4.0 授權