vue-router传参的4种方式超详细讲解

作者:秋田君 时间:2024-04-27 15:48:21 

一、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>

工作中经常用的也就是上面的几种传参方式,完结~ 

来源:https://blog.csdn.net/qq_42696432/article/details/125400186

标签:vue-router,传参
0
投稿

猜你喜欢

  • 用Python中的字典来处理索引统计的方法

    2022-05-28 19:43:45
  • python中翻译功能translate模块实现方法

    2021-05-09 17:02:33
  • python用tkinter实现一个gui的翻译工具

    2022-12-13 11:30:48
  • SQL Server免费版的安装以及使用SQL Server Management Studio(SSMS)连接数据库的图文方法

    2024-01-15 03:45:14
  • 解决图片撑大问题

    2009-09-22 14:51:00
  • Python3之手动创建迭代器的实例代码

    2021-10-15 21:00:30
  • python可视化分析的实现(matplotlib、seaborn、ggplot2)

    2021-10-20 13:59:21
  • Python用二分法求平方根的案例

    2021-09-27 10:05:01
  • mysql8.0.19基础数据类型详解

    2024-01-25 22:38:57
  • python 类的基础详解与应用

    2021-01-04 08:57:37
  • 如何运用python读写CSV文件

    2021-11-13 04:35:36
  • layui使用button按钮 点击出现弹层 弹层中加载表单的实例

    2024-05-02 17:22:15
  • python实现图像识别的示例代码

    2022-09-11 04:48:40
  • Python unittest单元测试openpyxl实现过程解析

    2023-06-17 10:54:31
  • MySQL 那些常见的错误设计规范,你都知道吗

    2024-01-25 18:19:36
  • python被修饰的函数消失问题解决(基于wraps函数)

    2021-07-22 17:32:34
  • Python图像处理之直线和曲线的拟合与绘制【curve_fit()应用】

    2021-01-28 10:30:49
  • 使用 GUID 值来作为数据库行标识讲解

    2024-01-24 01:10:24
  • Django 中使用流响应处理视频的方法

    2021-01-12 20:55:13
  • python库-dotenv包 及 .env配置文件详解

    2023-09-08 20:22:38
  • asp之家 网络编程 m.aspxhome.com