vue-router路由传递的四种方式超详细

Vue路由传递参数的四种方式

一、router-link路由导航方式传参

父组件:<router-link to="/跳转到的路径/传入的参数"></router-link>
子组件:this.$route.params.content接受父组件传递过来的参数

例如:
路由配置:

bashbash{path:'/father/son/:num',name:A,component:A}```

地址栏中的显示:

http://localhost:8080/#/father/son/44

调用方法:

<router-link to="/father/son/传入的参数">父亲组件<router-link>
 子组件通过  this.$route.params.num 接受参数

二、调用$router.push实现路由传参

父组件:通过实践触发,跳转代码

<button @click="clickHand(123)">push传参</button>
  methods: {
    clickHand(id) {
      this.$router.push({path: `/d/${id}`})
    }
  }

路由配置

{path: '/d/:id', name: D, component: D}

地址栏中显示:

http://localhost:8080/d/123

子组件接受参数方式

mounted () {
  this.id = this.$route.params.id
}

三、通过路由属性name匹配路由,再根据params传递参数

父组件:

<button @click="ClickByName()">params传参</button>
    ClickByName() {
      this.$router.push({
        name: 'B',
        params: {
          context: '吴又可吴又可吴又可'
        }
      })
    }

路由配置:路径后不需要在加上传入的参数,但是name必须和父组件中的name一致

{path: '/b', name: 'B', component: B}

地址栏中的显示:地址栏不会带有传入的参数,而且再次刷新页面后参数会丢失

http://localhost:8080/#/b

子组件接收参数的方式:

<template>
  <div id="b">
    This is page B!
    <p>传入参数:{{this.$route.params.context}}</p>
  </div>
</template>

四、通过query来传递参数

父组件:

<button @click="clickQuery()">query传参</button>
    clickQuery() {
      this.$router.push({
        path: '/c',
        query: {
          context: '吴又可吴又可'
        }
      })
    }

路由配置:不需要做任何修改

{path: '/c', name: 'C', component: C}

地址栏中的显示(中文转码格式):

http://localhost:8080/#/c?sometext=%E8%BF%99%E6%98%AF%E5%B0%8F%E7%BE%8A%E5%90%8C%E5%AD%A6

子组件接受方法:

<template>
  <div id="C">
    This is page C!
    <p>这是父组件传入的数据: {{this.$route.query.context}}</p>
  </div>
</template>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

结果才重要

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值