Router传参的几种方式

一、普通不携带参数

  1. 父组件代码
<!-- app.vue -->
<router-link to="/user">
  1. 路由配置
// router/index.js
{
path: '/user',
name: 'User',
component: User
}
  1. 导航栏显示
http://localhost:8082/#/user

二、携带参数的几种方法

  1. 父组件代码
<!-- app.vue -->
<router-link :to="`/user/${id}`">
<script>
data() {
return {
id:123
}
}
</script>
  1. 路由配置
// router/index.js
{
path: '/user/:id',
name: 'User',
component: User
}
  1. 导航栏显示
http://localhost:8082/#/user/123
  1. 子组件获取
// 通过 $route.params 获取所有传递的参数对象
this.$route.params
// 通过指定key值获取准确的参数
this.$route.params.id

$router.push()

通过点击触发,直接跳转到指定页面

  1. 父组件代码
<!-- app.vue -->
<button @click="goUser(456)">this.$router.push()-传参</button>
<script>
data() {
methods: {
goUser(id) {
this.$router.push({
// 直接访问地址,类似第一种方式,只是一个是路由组件,一个是点击事件触发
path: `/user/${id}`
})
}
}
}
</script>
  1. 路由配置
// router/index.js
{
path: '/user/:id',
name: 'User',
component: User,
}
  1. 导航栏显示
http://localhost:8082/#/user/456
  1. 子组件获取
// 通过 $route.params 获取所有传递的参数对象
this.$route.params
// 通过指定key值获取准确的参数
this.$route.params.id

params

params 只能与 name 一起使用

跳转后不会将参数拼接到 url 上,刷新页面后参数会丢失

  1. 父组件代码
<!-- app.vue -->
<button @click="goUser(789)">params-传参</button>
<script>
data() {
methods: {
goUser(id) {
this.$router.push({
// name 必须与路由的 name 一致
name: 'User',
params: {
id
}
})
}
}
}
</script>
  1. 路由配置
// router/index.js
{
path: '/user',
name: 'User',
component: User,
}
  1. 导航栏显示
http://localhost:8082/#/user
  1. 子组件获取
// 通过 $route.params 获取所有传递的参数对象
this.$route.params
// 通过指定key值获取准确的参数
this.$route.params.id

query

query 可以和 name 或者 path 一起搭配使用

跳转后在 url 后面拼接参数:?id=abc,非重要数据可以这样传,像密码之类使用 params

  1. 父组件代码
<!-- app.vue -->
<button @click="goUser('abc')">query-传参</button>
<script>
data() {
methods: {
goUser(id) {
this.$router.push({
// 直接填写 path ,或者使用 name
// path: '/user',
name: 'User'
// 传参使用 query
query: {
id
}
})
}
}
}
</script>
  1. 路由配置
// router/index.js
{
path: '/user',
name: 'User',
component: User,
}
  1. 导航栏显示
http://localhost:8082/#/User?id=abc
  1. 子组件获取
// 通过 $route.query 获取所有传递的参数对象
this.$route.query
// 通过指定key值获取准确的参数
this.$route.query.id
posted @   如是。  阅读(1725)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示