Vue路由传参的几种方式

vue路由传参是指嵌套路由时父路由向子路由传递参数,否则操作无效

一、利用"router-link"路由导航

父组件:

使用 <router-link to = "/跳转路径/传入的参数"></router-link>

例如:<router-link to="/a/123">routerlink传参</router-link>

子组件:

使用 this.$route.params.num 接收父组件传递过来的参数

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

路由配置:{ path: '/a/:num', name: A, component: A }

地址栏中的显示:http://localhost:8080/#/a/123

 

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

父组件: 绑定事件,编写跳转代码

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

子组件this.$route.params.id接收父组件传递过来的参数

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

路由配置{path: '/d/:id', name: D, component: D}

地址栏中的显示http://localhost:8080/#/d/123

 

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

父组件: 匹配路由配置好的属性名

复制代码
<button @click="deliverByName()">params传参</button> 
    
deliverByName () {
this.$router.push({ name: 'B', params: { sometext: '熊出没' } }) }
复制代码

子组件:

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

路由配置:{path: '/b', name: 'B', component: B}   路径后面不需要再加传入的参数,但是name必须和父组件中的name一致

地址栏中的显示: http://localhost:8080/#/b   可以看出地址栏不会带有传入的参数,且再次刷新页面后参数会丢失

 

四、通过query来传递参数

父组件

复制代码
<button @click="deliverQuery()">query传参</button>
    deliverQuery () { 
      this.$router.push({
        path: '/c', 
        query: {
          sometext: '我是光头强' 
        } 
      }) 
    }
复制代码

子组件

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

 

路由配置:{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

相当于再url地址后面拼接参数(中文转码

 

posted @   有只小菜猫  阅读(986)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示