路由传参

2023-03-27  本文已影响0人  扶得一人醉如苏沐晨

一、路由传参

1.1、路由跳转有几种方式?

比如: A->B
声明式导航: router-link (务必要有to属性) ,可以实现路由的跳转
编程式导航: 利用的是组件实例的$router.push | replace方法,可以实现路由的跳转。(可以书写一些自己业务)

1.2、路由传参,参数有几种写法?

params参数: 属于路径当中的一部分,需要注意,在配置路由的时候,需要占位
query参数: 不属于路径当中的一部分,类似于ajax中的querystring/home?k=v&kv=

一:params 传参(显示参数)

params 传参(显示参数)又可分为 声明式 和 编程式 两种方式

1.1、声明式 router-link

该方式是通过 router-link 组件的 to 属性实现,该方法的参数可以是一个字符串路径,或者一个描述地址的对象。使用该方式传值的时候,需要子路由提前配置好参数,例如:

//子路由配置
{
 path: '/child/:id',
 component: Child
}
//父路由组件
<router-link :to="/child/123">进入Child路由</router-link>

1.2、编程式 this.$router.push

使用该方式传值的时候,同样需要子路由提前配置好参数,例如:

//子路由配置
{
 path: '/child/:id',
 component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
  path:'/child/${id}',
})

在子路由中可以通过下面代码来获取传递的参数值

this.$route.params.id

二、params 传参(不显示参数)

params 传参(不显示参数)也可分为 声明式 和 编程式 两种方式,与方式一不同的是,这里是通过路由的别名 name 进行传值的

2.1、声明式 router-link

该方式也是通过 router-link 组件的 to 属性实现,例如:

<router-link :to="{name:'Child',params:{id:123}}">进入Child路由</router-link>

2.2、编程式 this.$router.push

使用该方式传值的时候,同样需要子路由提前配置好参数,不过不能再使用 :/id 来传递参数了,因为父路由中,已经使用 params 来携带参数了,例如:

//子路由配置
{
 path: '/child,
 name: 'Child',
 component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
  name:'Child',
  params:{
   id:123
  }
})

在子路由中可以通过下面代码来获取传递的参数值

this.$route.params.id

上述这种利用 params 不显示 url 传参的方式会导致在刷新页面的时候,传递的值会丢失

方式三:query 传参(显示参数),这里跳转也可以用path跳转

query 传参(显示参数)也可分为 声明式 和 编程式 两种方式

##3.1、声明式 router-link

该方式也是通过 router-link 组件的 to 属性实现,不过使用该方式传值的时候,需要子路由提前配置好路由别名(name 属性),例如:

//子路由配置
{
 path: '/child,
 name: 'Child',
 component: Child
}
//父路由组件
<router-link :to="{name:'Child',query:{id:123}}">进入Child路由</router-link>

3.2、编程式 this.$router.push

使用该方式传值的时候,同样需要子路由提前配置好路由别名(name 属性),例如:

//子路由配置
{
 path: '/child,
 name: 'Child',
 component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
  name:'Child',
  params:{
   id:123
  }
})

在子路由中可以通过下面代码来获取传递的参数值

this.$route.query.id

四、props传参

4.1、props为布尔值

只能把params的参数传递过去

path:"/search/:keyword?",
component: Search,
meta:{show:true},
name:"search",
props:true

路由组件通过props接收

export default {
   name:'',
   //路由组件可以传递props
   props:['keyword']
}

4.2、props为对象

path:"/search/:keyword?",
component: Search,
meta:{show:true},
name:"search",
props:{id:'123'}

路由组件通过props接收

export default {
   name:'',
   //路由组件可以传递props
   props:['id']
}

4.3、props为函数(参数就是$route)

path:"/search/:keyword?",
component: Search,
meta:{show:true},
name:"search",
props:($route)=>({keyword:$route.params.keyword,k:$route.query.k})

路由组件通过props接收

export default {
   name:'',
   //路由组件可以传递props
   props:['keyword','key']
}
上一篇 下一篇

猜你喜欢

热点阅读