iT邦幫忙

2025 iThome 鐵人賽

DAY 25
0
Vue.js

新手學習Vue.js與實作之旅系列 第 25

Day25 Vue Router (II)

  • 分享至 

  • xImage
  •  

在昨天介紹使用 Vue Router 的內容中,有提到在 router 資料夾中的 index.js 檔案內寫入 router 規則,今天將更詳細說明 Vue Router 的路由相關設定與功能。

history 是什麼?

history 是 Vue Router 處理前端路由的方式,可以分為以下兩種方式:

  • Hash Mode
    將 history 設定為 createWebHashHistory(),其 URL 會包含 # (井號),
    例如: http://example.com/#user
  • HTML5 (History API) Mode
    將 history 設定為 createWebHistory(),其 URL 看起來像正常的網址,
    例如: http://example.com/user , Vue Router 預設是採取此方式。

routes 是什麼?

routes 可以處理路徑與 Vue 實體元件的對應,屬於陣列型態的內容。

動態路由

透過在路徑中使用 : (冒號)來定義動態參數,讓不同的 URL 路徑能夠對應到同一個路由。

以下是官方文件的範例

使用 : id 作為動態參數可以匹配任何值,例如:/users/123、/users/abc 都會匹配到這個路由,其匹配到的值會存在 $route.params.id 中。

import User from './User.vue'

const routes = [
  { path: '/users/:id', component: User },
]

在模板中使用插植表達式寫入 $route.params.id ,畫面會呈現出 URL 中 : id 的實際值,例如: URL 是 /users/123,頁面就會顯示 User 123。

<template>
  <div>
    User {{ $route.params.id }}
  </div>
</template>

巢狀路由

巢狀路由又可以稱為嵌套路由,透過在 routes 增加一個 children 陣列,實現在父元件的<router-view>中再嵌套子元件的<router-view>,由於以 / 開頭的巢狀路徑將被視為根路徑,因此 children 裡面的 path 不要加上 / 開頭。

以下是官方文件的範例

<!-- App.vue -->
<template>
  <router-view />
</template>
<!-- User.vue -->
<template>
  <div class="user">
    <h2>User {{ $route.params.id }}</h2>
    <router-view />
  </div>
</template>

當訪問 /user/123/profile 時,會在 App.vue 的 <router-view> 渲染 User 元件的內容,接著在 User.vue 的 <router-view> 渲染 UserProfile 元件的內容。

const routes = [
  { //父路由:渲染 User 元件
    path: '/user/:id',
    component: User,
    //子路由:在 User 元件內渲染 UserProfile 或 UserPosts 元件
    children: [
      {
        path: 'profile',
        component: UserProfile,
      },
      {
        path: 'posts',
        component: UserPosts,
      },
    ],
  },
]

具名路由

透過指定 name 屬性作為元件路由的依據。

以下是官方文件的範例

const routes = [
  {
    path: '/user/:username',
    name: 'profile', 
    component: User
  }
]

<router-link>使用 name 和參數,建立一個指向 /user/erina 的連結。

<router-link :to="{ name: 'profile', params: { username: 'erina' } }">
  User profile
</router-link>

參考資源

https://book.vue.tw/CH4/4-3-router-link.html
https://router.vuejs.org/zh/guide/
https://hackmd.io/@CynthiaChuang/Vue-Study-Notes-Contents/%2F%40CynthiaChuang%2FVue-Study-Notes-Unit10%23%25E4%25BD%25BF%25E7%2594%25A8-Vue-Router-%25E5%258F%258A%25E9%2585%258D%25E7%25BD%25AE%25E8%25B7%25AF%25E7%2594%25B1%25E6%2596%2587%25E4%25BB%25B6


上一篇
Day24 Vue Router (I)
下一篇
Day26 Vue Router (III)
系列文
新手學習Vue.js與實作之旅30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言