怎么定义Vue Router 的动态路由?怎么获取传过来的动态参数?
在 Vue Router 中,动态路由是指在路径中使用变量(占位符)来匹配不同的页面或组件内容。
一、定义动态路由
在 Vue Router 配置中使用 : 定义动态参数,例如:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import UserDetail from '../views/UserDetail.vue'
const routes = [
{
path: '/user/:id',
name: 'UserDetail',
component: UserDetail
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
:id 就是一个动态参数,可以匹配 /user/1、/user/abc 等路径。
二、获取动态参数
在 Vue 组件中获取参数(两种方式):
1. 通过 useRoute()(Vue 3 + Composition API)
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
const userId = route.params.id
</script>
2. 通过 this.$route.params(Options API)
export default {
mounted() {
console.log(this.$route.params.id)
}
}
三、完整示例
路由配置
// /user/:id
{
path: '/user/:id',
component: () => import('@/views/UserDetail.vue')
}
UserDetail.vue
<template>
<div>User ID: {{ userId }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
const userId = route.params.id
</script>
四、可选参数
{
path: '/user/:id?',
component: UserDetail
}
/user 和 /user/123 都可以匹配。
对比(Vue 2 vs Vue 3)
功能 | Vue 2 (Options API) | Vue 3 (Composition API) |
---|---|---|
获取参数 | this.$route.params.id |
useRoute().params.id |
定义路由 | path: '/user/:id' |
相同 |
响应参数变化 | watch: { '$route.params.id': fn } |
watch(() => route.params.id, fn) |