Vue2:路由传参(query传参和动态路由传参)
动态路由传参
路由传参有2种方式
传递的参数都在路由信息对象中: 路由对应的组件中获取 this.$route
1、query传参
query传参是把参数放在querystring字段中
//2种传参: <router-link to="/xx?name=karen&pwd=123">go</router-link> this.$router.push({path:"/xx",query:{name:"karen",pwd:123}}) //在路由匹配的组件中获取数据: mounted(){let queryObj=this.$route.query}
一共4种
<router-link to="/info?id=123456&pwd=abc123">go info</router-link><br>
<router-link :to="{path:'/info',query:{a:1000,b:200}}">go info</router-link><br>
this.$router.push("/info?q=abc1234&w=hello")
this.$router.push({path:"/info",query:{id:123457,age:20,name:"karen"}})
目标页面:在created之后的所有地方
this.$route.query 接受获取数据,如果没有传参 这个值就没有
2、动态路由传参
动态路由传参就是把参数放在pathname中
//设计: const router=new VueRouter({ routes:[ {path:"/home/:id",component:()=>import("./home.vue")}, {path:"/about",component:()=>import("./about.vue")}] }) //2种传参: <router-link to="/home/123">go</router-link> this.$router.push({path:"/home",params:{id:123}}) // 如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path: //在路由匹配的组件中获取数据: mounted(){let paramsObj=this.$route.params}
跳转
<router-link to="/news/参数">news</router-link><br>
<router-link :to="{name:"news",params:{id:参数}}">news</router-link><br>
this.$router.push("/news/参数")
this.$router.push({name:"news",params:{id:参数}})//必须用name跳路由
注:this.$route.params 接受获取数据,如果没有传参 这个值就没有
浙公网安备 33010602011771号