Vue Router 的params和query傳參的使用和區別(詳盡)
1.vue之this.$route.query和this.$route.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;
//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;
//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傳參,但是在跳轉的時候沒有傳這個引數,會導致跳轉失敗或者頁面會沒有內容。
總結
- 傳參可以使用params和query兩種方式。
- 使用params傳參只能用name來引入路由,即push裡面只能是name:’xxxx’,不能是path:’/xxx’,因為params只能用name來引入路由,如果這裡寫成了path,接收引數頁面會是undefined!!!。
- 使用query傳參使用path來引入路由。
- params是路由的一部分,必須要在路由後面新增引數名。query是拼接在url後面的引數,沒有也沒關係。
- 二者還有點區別,直白的來說query相當於get請求,頁面跳轉的時候,可以在位址列看到請求引數,而params相當於post請求,引數不會再位址列中顯示。
轉載https://blog.csdn.net/lsy__lsy/article/details/79991955,原版地址
一、this.$route.query的使用
1、router/index.js
{
path:'/mtindex',
component: mtindex,
//新增路由
children:[
{
path:':shopid',
component:guessdetail
}
]
},
2、傳引數
this.$router.push({
path: '/mtindex/detail', query:{shopid: item.id}
});
3、獲取引數
this.$route.query.shopid
4、url的表現形式(url中帶有引數)
http://localhost:8080/#/mtindex/detail?shopid=1
二、this.$route.params
1、router/index.js
{
path:'/mtindex',
component: mtindex,
//新增路由
children:[
{
path:"/detail",
name:'detail',
component:guessdetail
}
]
},
2、傳引數(params相對應的是name query相對應的是path)
this.$router.push({
name: 'detail', params:{shopid: item.id}
});
3、獲取引數
this.$route.params.shopid
4、url的表現形式(url中沒帶引數)
http://localhost:8080/#/mtindex