82
Vue 3 學習之旅
路由管理
Day 82: 動態路由匹配
·6 分鐘閱讀·路由管理
摘要
動態路由允許我們將一個 URL 模式匹配到同一個元件,常用於處理基於 ID 的資源顯示,如使用者個人資料頁或商品詳情頁。
定義與說明
我們可以在路由路徑中使用「動態區段」(dynamic segment),它以冒號 :
開頭。這些區段的值會被捕獲,並作為「路由參數」 route.params
暴露給元件。
實作範例
路由配置
// router/index.js
const routes = [
// :id 是一個動態區段
{ path: '/users/:id', name: 'user', component: UserView }
];
UserView.vue
<!-- UserView.vue -->
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
// 透過 route.params.id 來獲取 URL 中的 id 值
const userId = route.params.id;
</script>
<template>
<h1>使用者 ID: {{ userId }}</h1>
</template>
結論
動態路由匹配是建構 RESTful 風格應用的關鍵。它讓我們能用單一元件處理一整類的路徑,大幅提升了程式碼的複用性。
動態路由 路由參數 RESTful