vue-router传递参数3种方法

版权声明:本文为博主原创文章,转载请注明出处 thx~ https://blog.csdn.net/x550392236/article/details/88555153

第一种: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 
    

猜你喜欢

转载自blog.csdn.net/x550392236/article/details/88555153