Vue 路由之间传递参数

方式一:直接调用$router.push 实现携带参数的跳转

showDetail(id) {
    this.$router.push({
      path: `/detail/${id}`,
    })

需要对应路由配置如下:

   {
     path: '/detail/:id',
     name: 'Detail',
     component: Detail
   }

很显然,需要在path中添加/:id来对应 $router.push 中path携带的参数。在子组件中可以使用以下方式来获取传递的参数值。

this.$route.params.id

特别注意,获取参数是用的 route,而不是route,而不是router

这种方式最后得到的链接是这个样子的:

http://Llocalhost/detail/10000

方式二:通过路由属性中的name来确定匹配的路由,通过params来传递参数。

    this.$router.push({
          name: 'Detail',
          params: {
            id: id
          }
        })

对应路由配置: 注意这里不能使用:/id来传递参数了,因为父组件中,已经使用params来携带参数了。

{
     path: '/detail',
     name: 'Detail',
     component: Detail
   }

子组件获取参数:

this.$route.params.id

方式三:使用path来匹配路由,然后通过query来传递参数

这种情况下 query传递的参数会显示在url后面?id=?

    this.$router.push({
          path: '/detail',
          query: {
            id: id
          }
        })

对应路由配置:

{
     path: '/detail',
     name: 'Detail',
     component: Detail
   }

对应子组件来获取参数

this.$route.query.id
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容