vue-router路由传参之query和params

首先简单来说明一下$router和$route的区别

//$router : 是路由操作对象,只写对象
//$route : 路由信息对象,只读对象

//操作 路由跳转

this.$router.push({
  name:'hello',
  params:{
    name:'word',
    age:'11'
  }
})

//读取 路由参数接收

this.name = this.$route.params.name;
this.age = this.$route.params.age;

1·query传递参数
我看了很多人都说query传参要用path来引入,params传参要用name来引入,只是我测试了一下,query使用name来引入也可以传参,使用path也可以。如果有人知道原因可以告诉我一下,谢谢!

//query传参,使用name跳转

this.$router.push({
  name:'second',
  query: {
    queryId:'20180822',
    queryName: 'query'
  }
})

//query传参,使用path跳转

this.$router.push({
  path:'second',
  query: {
    queryId:'20180822',
    queryName: 'query'
  }
})

//query传参接收

this.queryName = this.$route.query.queryName;
this.queryId = this.$route.query.queryId;

最终不管是path引入还是name引入效果都一样如下图


2·params传递参数
注:使用params传参只能使用name进行引入

使用params传参

//params传参 使用name
this.$router.push({
  name:'second',
  params: {
    id:'20180822',
    name: 'query'
  }
})

//params接收参数

this.id = this.$route.params.id ;
this.name = this.$route.params.name ;

//路由

{
  path: '/second/:id/:name',
  name: 'second',
  component: () => import('@/view/second')
}

效果如下图


需要注意的是:

params是路由的一部分,必须要在路由后面添加参数名。query是拼接在url后面的参数,没有也没关系。
params一旦设置在路由,params就是路由的一部分,如果这个路由有params传参,但是在跳转的时候没有传这个参数,会导致跳转失败或者页面会没有内容。
如果路由后面没有 /:id/:name效果如下图,地址栏没有参数


但是如果你刷新一下,就会发现页面失败,效果如下图


因此我们不可能让用户不要刷新,所以我们必须在路由后面加上 /:id/:name

如果使用path进行传参
//params传参 使用path

this.$router.push({
  path:'second',
  params: {
    id:'20180822',
    name: 'query'
  }
})

//params接收参数

this.id = this.$route.params.id ;
this.name = this.$route.params.name ;

3.总结
传参可以使用params和query两种方式。
使用params传参只能用name来引入路由,即push里面只能是name:’xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!。
使用query传参使用path来引入路由。
params是路由的一部分,必须要在路由后面添加参数名。query是拼接在url后面的参数,没有也没关系。
二者还有点区别,直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显示。

【参考文章】

今天做项目时踩到了vue-router传参的坑(query和params),所以决定总结一下二者的区别。

直接总结干货!!!

1.query方式传参和接收参数

传参: 
this.$router.push({
        path:'/xxx',
        query:{
          id:id
        }
      })
  
接收参数:
this.$route.query.id

注意:传参是this.$router,接收参数是this.$route,这里千万要看清了!!!

this.$router 和this.$route有何区别?
在控制台打印两者可以很明显的看出两者的一些区别:

clipboard.png

  • 1.$router为VueRouter实例,想要导航到不同URL,则使用$router.push方法
  • 2.$route为当前router跳转对象,里面可以获取name、path、query、params等

2.params方式传参和接收参数

传参: 
this.$router.push({
        name:'xxx',
        params:{
          id:id
        }
      })
  
接收参数:
this.$route.params.id

注意:params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!

另外,二者还有点区别,直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显示

.

猜你喜欢

转载自www.cnblogs.com/jianxian/p/11975841.html