路由传参query与params区别
文章类型:Vue
发布者:hp
发布时间:2026-07-05
在前端路由开发中,经常需要在页面间传递参数。Vue Router 提供了两种主要的传参方式:params 和 query。
URL 形式:/user/123 或 /article/abc
/user/:id// 路由定义
{ path: '/user/:id', component: User }
// 传参方式
this.$router.push({ name: 'user', params: { id: 123 }})
// 或者
this.$router.push('/user/123')
// 接收参数
this.$route.params.id // 输出: 123URL 形式:/user?id=123&name=tom
? 拼接在 URL 后面// 传参方式
this.$router.push({
path: '/user',
query: { id: 123, name: 'tom' }
})
// 接收参数
this.$route.query.id // 输出: 123
this.$route.query.name // 输出: tom| 特性 | params | query |
|---|---|---|
| URL 显示 | /user/123 | /user?id=123 |
| 路由定义 | 需要定义 :id | 不需要 |
| 参数必需性 | 通常必需 | 可选 |
| 使用场景 | RESTful API、资源标识 | 筛选、搜索、可选配置 |
| 美观程度 | 更简洁 | 参数多时较长 |
// ✅ 推荐:查看用户详情
/user/123
// ✅ 推荐:查看文章详情
/article/abc-def-ghi
// ✅ 推荐:编辑项目
/project/456/edit
// ✅ 推荐:搜索用户列表
/users?keyword=john&page=1&pageSize=10
// ✅ 推荐:筛选文章
/articles?category=tech&tag=vue&sort=latest
// ✅ 推荐:带状态的列表页
/orders?status=pending&startDate=2024-01-01// ❌ 错误:params 不能配合 path 使用
this.$router.push({
path: '/user',
params: { id: 123 } // 参数会丢失
})
// ✅ 正确:params 配合 name 使用
this.$router.push({
name: 'user',
params: { id: 123 }
})选择 params 还是 query 主要取决于参数的性质:
paramsquery合理使用这两种传参方式,能让你的路由结构更加清晰、语义化,提升代码的可维护性。
暂无评论,快来发表第一条评论吧~