1. 动态路由参数(路由路径参数)
在路由定义中使用 :param,适合必需参数:
// 路由配置
{
path: '/user/:id',
name: 'User',
component: User
}
// 跳转方式
// 方式1:声明式导航
<router-link :to="'/user/' + userId">用户</router-link>
// 方式2:编程式导航
this.$router.push(`/user/${userId}`)
this.$router.push({ path: `/user/${userId}` })
// 接收参数
this.$route.params.id
2. 查询参数(Query Parameters)
使用 ?key=value 格式,适合可选参数:
// 跳转方式
// 方式1:声明式导航
<router-link :to="{ path: '/user', query: { id: 123, name: '张三' } }">
// 方式2:编程式导航
this.$router.push({
path: '/user',
query: { id: 123, name: '张三' }
})
// 接收参数
this.$route.query.id // 123
this.$route.query.name // 张三
3. 命名路由 + 参数
配合路由的 name 属性和 params:
// 路由配置
{
path: '/user/:id',
name: 'UserDetail',
component: UserDetail
}
// 跳转方式
this.$router.push({
name: 'UserDetail',
params: { id: 123 }
})
// 接收参数(在Vue 2中需在路由配置中声明参数,Vue 3更灵活)
this.$route.params.id
4. Props 解耦
将路由参数作为组件的 props 接收:
// 路由配置
{
path: '/user/:id',
component: User,
props: true // 自动将 params 转为 props
// 或使用函数形式
props: route => ({
id: parseInt(route.params.id),
query: route.query.search
})
}
// 组件中直接使用
export default {
props: ['id', 'query']
}
5. 路由元信息(Meta Fields)
在路由配置中定义静态元数据:
{
path: '/admin',
component: Admin,
meta: {
requiresAuth: true,
role: 'admin'
}
}
// 访问
this.$route.meta.requiresAuth
6. 通过路由状态传递复杂对象(Vue 3推荐)
使用 state 属性传递不会显示在URL中的数据:
// Vue 3中(Vue Router 4)
router.push({
name: 'User',
state: {
userData: { id: 1, name: '张三' },
from: 'home'
}
})
// 接收
import { useRouter } from 'vue-router'
const route = useRoute()
console.log(route.state.userData)
不同方式的对比
| 方式 | 特点 | 是否显示在URL | 刷新是否保留 |
|---|---|---|---|
| 动态路由参数 | 必需参数,路径一部分 | 是 | 是 |
| 查询参数 | 可选参数,?key=value |
是 | 是 |
| params | 配合命名路由使用 | 否(默认) | 否 |
| props | 组件解耦 | 取决于来源 | 同上 |
| meta | 路由元信息 | 否 | - |
| state | 复杂对象传递 | 否 | 是(Vue 3) |
最佳实践建议
-
必需参数 :使用动态路由参数(如
/user/:id) -
可选参数/过滤条件 :使用查询参数(如
?page=1&filter=active) -
不暴露在URL的敏感数据 :使用
state(Vue 3)或 Vuex/Pinia -
组件复用和解耦:使用 props 模式
-
权限控制等:使用 meta 字段
注意事项
-
Vue Router 3/4 对
params的处理略有不同 -
使用
params时推荐配合命名路由 -
传递复杂对象时注意序列化问题
-
考虑用户体验:重要参数应体现在URL中以便分享和收藏