vue-router传递参数3种方法

第一种:get方法

传递值

<router-link :to="{path:'/test',query: { userId: 123,userName:'xia' }}">跳转</router-link><router-link :to="{name:'test',query: { userId: 123,userName:'xia' }}">跳转</router-link>

接收值(页面刷新的时候不会消失)

this.$route.query.userId  // 123
this.$route.query.userName  // xia

url上显示参数:http://localhost:8080/test?userId=123&userName=xia


第二种:post方法

传递值

<!-- 必须用 name:'test' -->
<router-link :to="{name:'test',params: { userId: 123,userName:'xia' }}">跳转</router-link>

<!-- 用 path:'/test' 无效 -->
<!-- <router-link :to="{path:'/test',params: { userId: 123,userName:'xia' }}">跳转</router-link> -->

接收值(页面刷新的时候就会消失)

this.$route.params.userId  // 123
this.$route.params.userName  // xia

url上不显示参数:http://localhost:8080/test


第三种:路由方法

传递值

// router.js
{
    path: '/test/:userId/:userName?', //?问号的意思是该参数不是必传项
    name: 'test',
    component: 'test.vue',
    props: true,
},
// App.vue
<router-link to="/test/123/xia">跳转</router-link>

接收值(页面刷新的时候不会消失)

this.$route.params.userId  // 123
this.$route.params.userName  // xia

url上显示参数:http://localhost:8080/test/123/xia


另外: 如果在链接上设置 replace 属性,当点击时,会调用 router.replace() 而不是 router.push(),于是浏览器不会留下 history 记录。(无法返回到上一页)

  <router-link :to="{ path: '/test'}" replace></router-link>

Tips:这里我简单说明下 $router$route 的区别:

  1. $router :是指整个路由实例,你可以操控整个路由,用法如下:
    this.$router.go(-1);  // 向前或者向后跳转n个页面,n可为正整数或负整数
    this.$router.push('/'); // 跳转到指定url路径,history栈中会有记录,点击返回会跳转到上个页面
    this.$router.replace('/'); // 跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面
    
  2. $route:是指当前路由实例$router跳转到的路由对象;路由实例可以包含多个路由对象,它们是**父子包含关系**.
    // 获取路由传递过来的参数
    this.$route.params.userId  
    this.$route.query.userName 
    
  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

猫老板的豆

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

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

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

打赏作者

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

抵扣说明:

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

余额充值