動態路由匹配和路由參數
動態路由匹配是 Vue Router 的一個強大功能,它允許你創建靈活且可重用的路由。您可以使用參數來捕獲 URL 的動態段,而不是為每個可能的值定義特定路由。這在處理具有唯一標識符的資源(如用戶配置文件、產品詳細信息或博客文章)時特別有用。路由參數使您能夠通過減少對硬編碼路由的需求來構建更易于維護和可擴展的應用程序。
了解動態路由匹配
動態路由匹配涉及定義具有可更改段的路由。這些段由路由參數表示,路由參數由冒號 (:
) 后跟名稱表示。例如, /users/:id
定義一個路由,該路由與任何以 /users/
開頭的 URL 匹配,后跟一個將作為 id
參數捕獲的動態分段。
基本示例
考慮您希望根據用戶 ID 顯示用戶配置文件的場景。您可以定義如下路由:
const routes = [{ path: '/users/:id', component: UserProfile }
]
在此示例中,:id
是 route 參數。當用戶導航到 /users/123
時,將呈現 UserProfile
組件,并且值 123
將作為 id
參數進行訪問。
訪問路由參數
在 UserProfile
組件中,您可以使用 $route.params
訪問 route 參數。
<template><div><h1>User Profile</h1><p>User ID: {{ userId }}</p></div>
</template><script>
export default {computed: {userId() {return this.$route.params.id;}}
}
</script>
在此組件中,userId
計算屬性從 $route.params
檢索 id
參數并將其顯示在模板中。
多個路由參數
您可以在單個路由中定義多個路由參數。例如,如果您有一個類似于 /products/:category/:id
的路由,則可以在組件中訪問 category
和 id
參數。
const routes = [{ path: '/products/:category/:id', component: ProductDetails }
]
<template><div><h1>Product Details</h1><p>Category: {{ category }}</p><p>Product ID: {{ productId }}</p></div>
</template><script>
export default {computed: {category() {return this.$route.params.category;},productId() {return this.$route.params.id;}}
}
</script>
在這種情況下,導航到 /products/electronics/456
將呈現 ProductDetails
組件,其中 category
設置為 electronics,id
設置為 456
。
高級路由參數匹配
Vue Router 提供了控制路由參數匹配方式的高級選項。這包括可選參數、正則表達式匹配等。
可選參數
有時,您可能希望 route 參數是可選的。您可以通過在參數名稱后添加問號 (?
) 來實現此目的。例如,/search/:query?
使 query
參數可選。
const routes = [{ path: '/search/:query?', component: SearchResults }
]
<template><div><h1>Search Results</h1><p v-if="query">Query: {{ query }}</p><p v-else>Enter a search query.</p></div>
</template><script>
export default {computed: {query() {return this.$route.params.query;}}
}
</script>
在此示例中,導航到 /search
將呈現不帶查詢的 SearchResults
組件,而導航到 /search/vue
將呈現查詢參數設置為
vue
的組件。
正則表達式匹配
您可以使用正則表達式為路由參數定義更具體的匹配條件。這是通過在參數名稱后的括號內添加正則表達式來完成的。例如, /users/:id(\\d+)
僅當 id
參數由一個或多個數字組成時,才會匹配。
const routes = [{ path: '/users/:id(\\d+)', component: UserProfile }
]
此路由將匹配 /users/123
,但不匹配 /users/abc
。
<template><div><h1>User Profile</h1><p>User ID: {{ userId }}</p></div>
</template><script>
export default {computed: {userId() {return this.$route.params.id;}},watch: {'$route.params.id': {handler(newId) {if (!/^\d+$/.test(newId)) {alert('Invalid User ID');this.$router.push('/'); // Redirect to home or another appropriate route}},immediate: true // Check on initial load}}
}
</script>
在此示例中,組件使用 watch
根據正則表達式驗證 id
參數。如果 ID
不是數字,則會顯示警報,并重定向用戶。
Catch-all 路由
您可以使用 catch-all 路由來匹配與任何其他已定義路由不匹配的任何 URL。這是通過使用星號 (*
) 作為路由路徑來完成的。例如,/*
將匹配任何 URL。
const routes = [{ path: '/users/:id', component: UserProfile },{ path: '/*', component: NotFound }
]
在此示例中,如果用戶導航到與 /users/:id
不匹配的 URL,則將呈現 NotFound
組件。
<template><div><h1>404 Not Found</h1><p>The requested page could not be found.</p></div>
</template>
優先權
定義路由時,定義路由的順序很重要。Vue Router 按照定義的順序匹配路由。因此,應在更通用的路由之前定義更具體的路由。
例如,如果您有以下路由:
const routes = [{ path: '/users/admin', component: AdminProfile },{ path: '/users/:id', component: UserProfile }
]
如果用戶導航到 /users/admin
,則將呈現 AdminProfile
組件,因為它是在 /users/:id
路由之前定義的。如果路由以相反的順序定義,則將改為呈現 UserProfile
組件,并將 id
設置為 admin
。
實際示例和演示
讓我們探索一些使用動態路由匹配和路由參數的實際示例。
博客文章示例
考慮一個博客應用程序,您希望在其中根據其獨特的 slug 顯示單個博客文章。
const routes = [{ path: '/blog/:slug', component: BlogPost }
]
<template><div><h1>{{ post.title }}</h1><p>{{ post.content }}</p></div>
</template><script>
export default {data() {return {post: {}};},mounted() {// Simulate fetching the blog post from an APIsetTimeout(() => {this.post = {title: 'My First Blog Post',content: 'This is the content of my first blog post.'};}, 500);}
}
</script>
在此示例中,BlogPost
組件根據 slug
參數獲取博客文章數據。
電子商務產品示例
在電子商務應用程序中,您可能希望根據產品 ID 顯示產品詳細信息。
const routes = [{ path: '/products/:id', component: ProductDetails }
]
<template><div><h1>{{ product.name }}</h1><p>Price: {{ product.price }}</p><p>{{ product.description }}</p></div>
</template><script>
export default {data() {return {product: {}};},mounted() {// Simulate fetching the product details from an APIsetTimeout(() => {this.product = {name: 'Awesome Product',price: 99.99,description: 'This is an awesome product.'};}, 500);}
}
</script>
在此示例中,ProductDetails
組件根據 id
參數獲取產品詳細信息。
帶參數的嵌套路由
您還可以將動態路由匹配與嵌套路由一起使用。例如,您可能有一個用于顯示用戶配置文件的路由和另一個用于顯示其設置的路由。
const routes = [{path: '/users/:userId',component: UserProfile,children: [{path: 'settings',component: UserSettings}]}
]
在這種情況下,UserSettings
組件既可以訪問父路由中的 userId
參數,也可以訪問其自己的路由中定義的任何其他參數。