在昨天介紹使用 Vue Router 的內容中,有提到在 router 資料夾中的 index.js 檔案內寫入 router 規則,今天將更詳細說明 Vue Router 的路由相關設定與功能。
history 是 Vue Router 處理前端路由的方式,可以分為以下兩種方式:
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