vue路由传参总结

一.Vue路由传参

 1.route-link路由导航

   在to跳转链接后传递参数,获取时需要在路由配置path时注明,才能通过$route.params拿到

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

// 跳转后拿到参数
mounted () {
  this.num = this.$route.params.num
}


//num是在配置路由路径时定义好的

{path: '/a/:num', name: A, component: A}

2.$router.push

 push跳转时在函数内定义好携带过去的参数,在下个页面通过$route.params拿到

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

//拿到参数
mounted () {
  this.id = this.$route.params.id
}

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

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

//写好要push去到的组件名

<button @click="deliverByName()">params传参</button>
    deliverByName () {
      this.$router.push({
        name: 'B',
        params: {
          sometext: '一只羊出没'
        }
      })
    }

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

//路由规则定义
{path: '/b', name: 'B', component: B}

4.通过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}

注:通过这种方式拿到的数据会显示在url中

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

总结:

1.传参的是this.$router,接收参数是this.$route,易混淆。前者是VueRouter的实例对象,而后者则是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象。

2.params是通过name属性传递数据给指定的组件,query是通过path的配置将数据传递到指定path的地址。

3.通过query传递的数据在刷新页面的时候不会消失,而params传递的数据刷新页面得时候会消失,可以通过本地存储解决。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值