Vue Router的传参方法主要包括以下三种:
一、路径参数(params)
传参方式:
在路由配置中,使用冒号(:)定义参数占位符,如
{ path: '/user/:id', component: User }。使用
this.$router.push方法,并通过params对象传递参数,如this.$router.push({ name: 'user', params: { id: 123 } })。获取参数方式:
在目标组件中,通过
this.$route.params来获取传递的参数,如this.$route.params.id。
二、查询参数(query)
传参方式:
查询参数不需要在路由配置中定义占位符。
使用
this.$router.push方法,并通过query对象传递参数,如this.$router.push({ path: '/search', query: { keyword: 'vue' } })。获取参数方式:
在目标组件中,通过
this.$route.query来获取传递的参数,如this.$route.query.keyword。
三、props传参
传参方式:
在路由配置中,将
props设置为true或传入一个函数。使用
this.$router.push方法传递参数,方式与路径参数类似,如this.$router.push({ name: 'user', params: { id: 123 } })。获取参数方式:
在目标组件中,通过
props接收参数,需要在组件中声明props,如props: ['id'],然后通过this.id访问参数。
此外,Vue Router的传参还可以通过<router-link>标签实现,其方式与this.$router.push类似,只需将参数放在to属性的对象中即可。
总结来说,Vue Router提供了多种灵活的传参方式,开发者可以根据具体需求选择合适的传参方式,以实现组件间的数据传递。

0条评论
点击登录参与评论