zoukankan      html  css  js  c++  java
  • Vue.js笔记(五) 路由传参的三种方式

    现有如下场景,点击父组件的button元素跳转到子组件中,并携带参数,便于子组件获取数据。

     <button  @click="handleChangePage(data.id)">预定</button>
    

    方案一:

        handleChangePage (id) {
          this.$router.push(`/detail/${id}`)
        }
    

    方案一,需要对应路由配置如下:

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

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

    this.$route.params.id
    

    方案二:

    父组件中:通过路由属性中的name来确定匹配的路由,通过params来传递参数。

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

    对应路由配置: 这里可以添加:/id 也可以不添加,不添加数据会在url后面显示,不添加数据就不会显示

        {
          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
    

    注意 在子组件中 获取参数的时候是route而不是router

  • 相关阅读:
    CF446C [DZY loves Fibonacci]
    [BZOJ2286] 消耗战
    [CF Round #278] Tourists
    BZOJ2553 [BJWC2011]禁忌
    NOI2018D2T1 屠龙勇士
    BZOJ2333 棘手的操作
    bzoj4196: [Noi2015]软件包管理器(树链剖分)
    bzoj1833: [ZJOI2010]count 数字计数(数位DP)
    bzoj1026: [SCOI2009]windy数(数位DP)
    bzoj3631: [JLOI2014]松鼠的新家(树上差分)
  • 原文地址:https://www.cnblogs.com/cpaulyz/p/12487222.html
Copyright © 2011-2022 走看看