在开发单页应用(SPA)时,我们经常需要根据不同的参数展示不同的页面内容。例如:
/user/123
/product/456
/search?keyword=vue
Vue Router 提供了多种灵活的传参方式来满足这些需求。本文将带你深入了解:
params
与 query
的区别;通过这篇文章,你将掌握如何在 Vue 项目中高效地进行路由传参。
方式 | 类型 | 是否出现在 URL 中 | 特点 |
---|---|---|---|
params (命名路由) |
参数传递 | ✅ 是(动态路由) | 需要配置动态路径 /user/:id |
params (非命名路由) |
参数传递 | ❌ 否(Vue 3+ 不推荐) | Vue 3 中需配合 name 使用 |
query |
查询字符串 | ✅ 是(URL 查询参数) | 简单易用,适合搜索、筛选等 |
meta |
自定义元信息 | ❌ 否 | 用于权限控制、页面标题等 |
props |
组件 props 传值 | ✅ 是(可选) | 将路由参数作为组件属性传递 |
params
进行动态路由传参router/index.js
){
path: '/user/:id',
name: 'UserDetail',
component: () => import('../views/UserDetail.vue')
}
注意:
:id
表示动态参数;/user/123
→ $route.params.id === '123'
this.$router.push({
name: 'UserDetail',
params: {
id: 123
}
})
效果:
/user/123
this.$route.params.id
获取参数export default {
mounted() {
console.log('用户 ID:', this.$route.params.id)
}
}
query
传参(查询字符串)适用于不需要路径匹配、仅需传递参数的场景,如搜索功能。
this.$router.push({
path: '/search',
query: {
keyword: 'vue router'
}
})
URL 显示为:/search?keyword=vue%20router
export default {
mounted() {
console.log('关键词:', this.$route.query.keyword)
}
}
params
与 query
的区别总结对比项 | params (动态路由) |
query |
---|---|---|
是否出现在路径中 | ✅ 是 | ✅ 是 |
是否需要配置动态路径 | ✅ 是 | ❌ 否 |
是否支持多个参数 | ✅ 是 | ✅ 是 |
是否可用于 SEO | ✅ 更好 | ❌ 一般 |
是否支持刷新保留数据 | ✅ 是 | ✅ 是 |
推荐用途 | 页面详情、资源标识 | 搜索、过滤、分页等 |
props
解耦路由参数为了更好的组件复用性,可以通过 props
将路由参数直接传递给组件。
props
{
path: '/user/:id',
component: UserDetail,
props: true // 将 $route.params 自动作为 props 传入组件
}
export default {
props: ['id'],
mounted() {
console.log('用户 ID:', this.id)
}
}
优势:
$route
,更易于测试和复用;嵌套结构中也可以传递参数,例如:
{
path: '/user/:userId',
component: UserLayout,
children: [
{
path: 'profile',
component: Profile
},
{
path: 'orders/:orderId',
component: OrderDetail
}
]
}
示例访问:
/user/123/profile
→ 可获取 userId = '123'
/user/123/orders/456
→ 可获取 userId = '123'
、orderId = '456'
场景 | 描述 |
---|---|
用户中心 | 根据用户 ID 展示不同资料页 /user/:id |
商品详情 | 根据商品 ID 加载对应数据 /product/:id |
搜索功能 | 使用 query 传递关键词 /search?keyword=xxx |
分页列表 | 使用 query 传递页码 /list?page=2 |
权限验证 | 结合 meta 与 params 控制页面访问权限 |
多级菜单 | 嵌套路由 + 动态参数组合使用 |
问题 | 解决方案 |
---|---|
刷新后 params 数据丢失 |
使用 query 或 localStorage 缓存 |
params 无法传对象 |
仅支持基本类型,复杂数据建议用 query 或接口请求 |
组件未正确接收参数 | 检查是否开启 props: true 或拼写错误 |
params 不生效(Vue 3) |
必须使用 name 跳转,不能使用 path |
参数编码问题 | 使用 encodeURIComponent() / decodeURIComponent() 手动处理特殊字符 |
传参方式 | 是否需要配置动态路径 | 是否出现在 URL | 是否推荐用于 SEO | 推荐程度 |
---|---|---|---|---|
params (动态路由) |
✅ 是 | ✅ 是 | ✅ 是 | ✅✅ 强烈推荐 |
params (非命名路由) |
❌ 否 | ❌ 否 | ❌ 否 | ⚠️ 已弃用(Vue 3) |
query |
❌ 否 | ✅ 是 | ✅ 是 | ✅✅ 强烈推荐 |
props |
✅ 是(基于 params ) |
✅ 是 | ✅ 是 | ✅ 推荐使用 |
meta |
❌ 否 | ❌ 否 | ❌ 否 | ✅ 用于配置信息 |
感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!