随笔 - 312  文章 - 0  评论 - 2  阅读 - 11万

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 接受获取数据,如果没有传参 这个值就没有

 

posted on   香香鲲  阅读(2160)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示