1、概念:
A、vue 路由传参的使用场景一般应用在父路由跳转到子路由时,携带参数跳转。
B、传参方式可划分为 params 传参和 query 传参;
C、而 params 传参又可分为在 url 中显示参数和不显示参数两种方式;
D、即vue路由传参的三种方式:query传参(显示参数)、params传参(显示参数)、params传参(不显示参数)
2、常见场景:
A、点击列表详情,跳转到详情内页,传递id参数获取详情数据。
B、在输入框输入内容后,点击搜索,跳转到搜索页面,并把输入的内容一起带到搜索页面
query 传参(显示参数)可分为 声明式 和 编程式 两种方式
1、声明式 router-link
该方式也是通过 router-link 组件的 to 属性实现,不过使用该方式传值的时候,需要子路由提前配置好路由别名 (name 属性),例如:
//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由组件
进入Child路由
2、编程式 this.$router.push
使用该方式传值的时候,同样需要子路由提前配置好路由别名 (name 属性),例如:
//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
name:'Child',
query:{
id:123
}
})
复制代码
接收参数:在子路由中可以通过下面代码来获取传递的参数值
this.$route.query
console.log( this.$route.query ) // { id:123 }
console.log( this.$route.query.id ) // 123
params 传参(显示参数)又可分为 声明式 和 编程式 两种方式
1、声明式 router-link
该方式是通过 router-link 组件的 to 属性实现,该方法的参数可以是一个字符串路径,或者一个描述地址的对象。使用该方式传值的时候,需要子路由提前配置好参数,例如:
//子路由配置
{
path: '/child/:id',
component: Child
}
//父路由组件
进入Child路由
2、编程式 this.$router.push
使用该方式传值的时候,同样需要子路由提前配置好参数,例如:
//子路由配置
{
path: '/child/:id',
component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
path:`/child/${id}`, // 模板字符串形式
})
接收参数:在子路由中可以通过下面代码来获取传递的参数值
this.$route.params.id
console.log( this.$route.params ) // { id:123 }
console.log( this.$route.params.id ) // 123
params传参(不显示参数)也可分为 声明式 和 编程式 两种方式,与方式一不同的是,这里是通过路由的别名 name 进行传值的
1、声明式router-link
该方式也是通过 router-link
组件的 to
属性实现,例如:
进入Child路由
2、编程式this.$router.push
使用该方式传值的时候,同样需要子路由提前配置好参数,不过不能再使用 :/id
来传递参数了,因为父路由中,已经使用params来携带参数了,例如:
//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
name:'Child',
params:{
id:123
}
})
接收参数:在子路由中可以通过下面代码来获取传递的参数值
this.$route.params.id
console.log( this.$route.params ) // { id:123 }
console.log( this.$route.params.id ) // 123