Vue Routerr使用query和params传参的使用和区别
因为最近在写关于Vue的项目(甩个链接,欢迎star: https://github.com/HeMin0919/cloudmusic)
总结一下使用query和params传参的使用
注意: 传参是this.$router
,接收参数是this.$route
//$router : 是路由操作对象,只写对象
//$route : 路由信息对象,只读对象
前言:params、query是什么?
params:/first/:id ,/first/123,/first/789 ,这里的id叫做params
query:/first?id=123 ,/first?id=456 ,这里的id叫做query。
1. query方式传参和接收参数
query传递的参数会显示在url后面?id=?
传参:
<router-link :to="{path:'/music',query:{val:val}}" replace>单曲</router-link>
this.$router.push({path:'/music',query:{ val: this.val }})
接收参数:
this.$route.query.val
对应路由配置:
{
path: '/music',
name: 'music',
component: music
}
PS: 当你点击<router-link>
时,这个方法会在内部调用,所以说,点击<router-link :to="...">
等同于调用router.push(...)。
详情见:编程式的导航
2. params方式传参和接收参数
传参:
<router-link :to="{name:'userInfo',params:{id:传的值}}">userInfo路由</router-link>
this.$router.push({path:`/userInfo/${this.id}`})
this.$router.push({name:'userInfo',params:{id:传的值}})
接收参数:
this.$route.params.id
对应路由配置:
{
path: '/userInfo/:id',
name: 'userInfo',
component: userInfo
}
注意: params传参,push里面只能是 name:‘xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!