本文实例讲述了vue路由传参的基本实现方式。分享给大家供大家参考,具体如下:前言vue 路由传参的使用场景一般都是应用在父路由跳转到子路由时,携带参数跳转。传参方式可划分为 params 传参和 query 传参,而 params 传参又可分为在 url 中显示参数和不显示参数两种方式,这就是vue路由传参的三种方式。paramsqueryparams方式一:params 传参(显示参数)paramsparams 传参(显示参数)又可分为 声明式 和 编程式 两种方式params
1、声明式 router-link
1、声明式 router-linkrouter-link该方式是通过 router-link 组件的 to 属性实现,该方法的参数可以是一个字符串路径,或者一个描述地址的对象。使用该方式传值的时候,需要子路由提前配置好参数,例如:router-link
//子路由配置
{
path: '/child/:id',
component: Child
}
//父路由组件
进入Child路由


//子路由配置
{
path: '/child/:id',
component: Child
}
//父路由组件
进入Child路由


2、编程式 this.$router.push
2、编程式 this.$router.pushthis.$router.push使用该方式传值的时候,同样需要子路由提前配置好参数,例如:
//子路由配置
{
path: '/child/:id',
component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({

path:'/child/${id}',
})


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

path:'/child/${id}',
})

在子路由中可以通过下面代码来获取传递的参数值
this.$route.params.id


this.$route.params.id

方式二:params 传参(不显示参数)paramsparams 传参(不显示参数)也可分为 声明式 和 编程式 两种方式,与方式一不同的是,这里是通过路由的别名 name 进行传值的paramsname
1、声明式 router-link
1、声明式 router-linkrouter-link该方式也是通过 router-link 组件的 to 属性实现,例如:router-link
进入Child路由


进入Child路由


2、编程式 this.$router.push
2、编程式 this.$router.pushthis.$router.push使用该方式传值的时候,同样需要子路由提前配置好参数,不过不能再使用 :/id 来传递参数了,因为父路由中,已经使用 params 来携带参数了,例如::/idparams
//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({

name:'Child',

params:{

id:123

}
})


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

name:'Child',

params:{

id:123

}
})

在子路由中可以通过下面代码来获取传递的参数值
this.$route.params.id


this.$route.params.id

注意:上述这种利用 params 不显示 url 传参的方式会导致在刷新页面的时候,传递的值会丢失params方式三:query 传参(显示参数)
queryquery 传参(显示参数)也可分为 声明式 和 编程式 两种方式
1、声明式 router-link
1、声明式 router-linkrouter-link该方式也是通过 router-link 组件的 to 属性实现,不过使用该方式传值的时候,需要子路由提前配置好路由别名(name 属性),例如:router-link
//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由组件
进入Child路由


//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由组件
进入Child路由


2、编程式 this.$router.push
2、编程式 this.$router.pushthis.$router.push使用该方式传值的时候,同样需要子路由提前配置好路由别名(name 属性),例如:
//子路由配置
{
path: '/child,
name: 'Child',
component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({

name:'Child',

params:{

id:123

}
})


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

name:'Child',

params:{

id:123

}
})

在子路由中可以通过下面代码来获取传递的参数值
this.$route.query.id


this.$route.query.id

希望本文所述对大家vue.js程序设计有所帮助。