Vue 路由传参的四种方式_vue路由传参可以传对象吗
在单页应用里,路由是连接页面与数据的桥梁。Vue Router 提供了四种方式把「参数」从地址栏、内存甚至编译期注入到组件。理解它们的差异,才能在面试和线上故障中游刃有余。
一、路径参数
把参数写进路径,直观且 SEO 友好。
// router.js
{
path: '/user/:userId',
component: User
}
访问 /user/42,组件内部:
const route = useRoute()
console.log(route.params.userId) // '42'
- 优点:可收藏、可分享、可被搜索引擎收录。
- 注意:使用正则捕获可限制类型,如 :userId(\\d+) 只接受数字。
二、查询参数
问号后的 key=value 对,天然支持多值与可选。
router.push({
path: '/user',
query: { id: 42, tab: 'profile' }
})
组件读取:
const route = useRoute()
console.log(route.query.tab) // 'profile'
- 场景:分页、筛选、弹窗状态。
- 陷阱:刷新页面后仍然存在,敏感信息需加密。
三、路由状态参数
state 不会出现在 URL,适合临时或敏感数据。
router.push({
path: '/confirm',
state: { orderId: 'xxx' }
})
组件读取:
import {
useHistoryState
} from '@vueuse/core'
console.log(history.state.orderId)
// 'xxx'
- 特性:刷新即消失,同源安全;常用于「下一步」导流。
- 限制:SSR 场景下为空,因为服务端没有浏览器 history。
四、路由 Props
把路径或查询自动映射为组件 Props,告别 $route 依赖。
{
path: '/user/:id',
component: User,
props: true
}
组件直接:
<script setup>
const props = defineProps(['id'])
</script>
- 进阶:传入函数可实现自定义映射,如把查询映射为对象。
- 测试:单元测试无需 mock $route,直接传 Props。
总结
路径参数让 URL 会说话,查询参数让 URL 会传表,状态参数让内存做快递,Props 让组件零耦合。掌握四种姿势,Vue 路由从此游刃有余。