文章

Vue Router 基礎

Vue Router 是 Vue.js 官方的路由管理庫,用來構建單頁應用程序(SPA)。通過 Vue Router,可以讓用戶在應用中導航不同的頁面,而不需要重新加載整個頁面。它與 Vue 組件緊密集成,使應用的導航體驗更流暢。

1. 什麼是 Vue Router?

Vue Router 的核心概念是 路由,它是將應用中的特定 URL 映射到 Vue 組件。每個路由都對應一個 Vue 組件,當用戶訪問特定的 URL 時,對應的 Vue 組件將被加載並顯示。

2. 安裝 Vue Router

如果使用的是 Vue CLI 創建的 Vue 3 應用,可以通過以下命令安裝 Vue Router:

1
npm install vue-router

如果使用的是 Vue 3 CDN 或 ES 模塊,你可以直接從 CDN 引入 Vue Router:

1
<script src="https://unpkg.com/vue-router@4"></script>

3. 基礎使用

1. 定義路由

首先,我們需要定義一組路由,每個路由都包含兩個基本要素:path(URL 路徑)和 component(組件)。

1
2
3
4
5
6
7
8
import { createRouter, createWebHistory } from 'vue-router';
import HomeComponent from './components/HomeComponent.vue';
import AboutComponent from './components/AboutComponent.vue';

const routes = [
  { path: '/', component: HomeComponent },
  { path: '/about', component: AboutComponent },
];

2. 創建路由實例

有了路由之後,我們需要創建一個路由實例。這可以通過 createRouter 方法來完成:

1
2
3
4
const router = createRouter({
  history: createWebHistory(), // 使用 HTML5 history 模式
  routes, // 路由配置
});

3. 在 Vue 應用中使用路由

在 Vue 應用中,路由需要與 Vue 實例結合起來。在主應用文件中導入並使用路由:

1
2
3
4
5
6
7
8
9
10
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 引入定義的 router

const app = createApp(App);

// 使用 router
app.use(router);

app.mount('#app');

4. Vue Router 重要屬性

1. router-view

<router-view> 是 Vue Router 提供的一個組件,用來顯示當前匹配到的組件。當用戶導航到不同的路由時,<router-view> 會渲染對應的 Vue 組件。

1
2
3
4
5
6
<template>
  <div>
    <h1>我的應用</h1>
    <router-view></router-view> <!-- 渲染對應的路由組件 -->
  </div>
</template>

<router-link> 是用來創建導航鏈接的組件。它類似於 HTML 的 <a> 標籤,但會自動管理應用的導航而不會導致頁面重新加載。

1
2
3
4
5
6
<template>
  <div>
    <router-link to="/">首頁</router-link>
    <router-link to="/about">關於我們</router-link>
  </div>
</template>

當用戶點擊這些 router-link 時,URL 會更新並加載對應的組件,但頁面不會重新加載,這就是單頁應用的特性。

5. 導航方式

1. to 屬性

可以使用 to 屬性來指定要導航的路徑:

1
<router-link to="/about">關於我們</router-link>

2. 編程式導航

除了使用 <router-link>,你還可以使用 Vue Router 提供的 API 進行編程式導航:

1
this.$router.push('/about'); // 導航到 /about

或使用命名路由:

1
this.$router.push({ name: 'about' });

6. 路由的進階功能

1. 動態路由

Vue Router 支持動態路由,可以用來處理路由參數。例如,展示某個用戶的詳細信息頁面:

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

UserComponent 中,你可以通過 this.$route.params.id 獲取路由參數:

1
2
3
4
5
export default {
  mounted() {
    console.log(this.$route.params.id);
  },
};

2. 命名路由

可以為每個路由指定一個名稱,這樣在導航時可以使用路由名稱而不是路徑:

1
2
3
4
5
6
7
const routes = [
  { path: '/', component: HomeComponent, name: 'home' },
  { path: '/about', component: AboutComponent, name: 'about' },
];

// 使用命名路由導航
this.$router.push({ name: 'about' });

3. 重定向

可以使用 redirect 屬性來將一個路由重定向到另一個路由:

1
2
3
const routes = [
  { path: '/old-path', redirect: '/new-path' },
];

4. 別名

路由還可以設置別名,使得一個路徑可以有多個 URL:

1
2
3
const routes = [
  { path: '/home', component: HomeComponent, alias: '/start' },
];

5. 導航守衛

Vue Router 提供了多種導航守衛(Navigation Guards),用來控制用戶的訪問行為。導航守衛是一些鉤子函數,它們在導航發生前後進行執行。

全局守衛

1
2
3
4
5
6
7
8
router.beforeEach((to, from, next) => {
  // 在每次導航前執行
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

路由中的守衛

1
2
3
4
5
6
7
8
9
10
11
12
13
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    beforeEnter: (to, from, next) => {
      if (!isAuthenticated()) {
        next('/login');
      } else {
        next();
      }
    },
  },
];

7. 路由模式

Vue Router 支持兩種導航模式:

  • 歷史模式(History Mode):使用 HTML5 的 history.pushState。需要後端支持,確保將所有路由重定向到 index.html
  • 哈希模式(Hash Mode):默認模式,URL 會包含 #,例如 http://example.com/#/about。這種模式不需要後端支持。

切換路由模式

可以通過設置 history 屬性來選擇不同的路由模式:

1
2
3
4
const router = createRouter({
  history: createWebHistory(), // HTML5 History 模式
  routes,
});

1
2
3
4
const router = createRouter({
  history: createWebHashHistory(), // Hash 模式
  routes,
});

總結

  • Vue Router 是 Vue.js 的官方路由管理庫,用於實現單頁應用中的頁面導航。
  • 基本組件 包括 router-view(顯示對應路由的組件)和 router-link(創建導航鏈接)。
  • 動態路由導航守衛重定向命名路由 是 Vue Router 提供的進階功能,能夠構建更加靈活的應用。

Vue Router 是單頁應用中實現導航的強大工具,能夠幫助開發者管理應用的頁面狀態並提升用戶體驗。

本文章以 CC BY 4.0 授權