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 >
    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 >
    This is page C!
    <p>这是父组件传入的数据: {{this.$route.query.context}}</p>
  </div>
</template>

工作中经常用的也就是上面的几种传参方式,完结~ 欢迎点赞收藏哦

补充知识:

vue-router传递参数的几种方式

vue-router传递参数分为两大类

1 编程式的导航 router.push

2声明式的导航

编程式的导航 router.push

编程式导航传递参数有两种类型:字符串、对象。

字符串

字符串的方式是直接将路由地址以字符串的方式来跳转,这种方式很简单但是不能传递参数:

this.$router.push("home");

对象

使用方法如下:

this.$router.push({ name: 'news', params: { userId: 123 }})

name:为路由的名字

获取参数

{{this.$route.params.userId}}

查询参数

使用方法如下:

this.$router.push({ path: '/news', query: { userId: 123 }});

获取参数

{{this.$route.query.userId}}

声明式的导航

字符串方式

click to news page

命名路由方式

click to news page

查询参数方式

click to news page

1.命名路由搭配params,刷新页面参数会丢失

2.查询参数搭配query,刷新页面数据不会丢失

3.接受参数使用this.$router后面就是搭配路由的名称就能获取到参数的值

原文地址:https://blog.csdn.net/qq_42696432/article/details/125400186