vue --- 路由傳參的幾種方式

方案一:

      getDescribe(id) {
//   直接調用$router.push 實現攜帶參數的跳轉
        this.$router.push({
          path: `/describe/${id}`,
        })

方案一,須要對應路由配置以下:javascript

   {
     path: '/describe/:id',
     name: 'Describe',
     component: Describe
   }

很顯然,須要在path中添加/:id來對應 $router.push 中path攜帶的參數。在子組件中能夠使用來獲取傳遞的參數值。java

this.$route.params.id

方案二:

父組件中:經過路由屬性中的name來肯定匹配的路由,經過params來傳遞參數。this

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

對應路由配置: 注意這裏不能使用:/id來傳遞參數了,由於父組件中,已經使用params來攜帶參數了。url

   {
     path: '/describe',
     name: 'Describe',
     component: Describe
   }

子組件中: 這樣來獲取參數spa

this.$route.params.id

方案三:

父組件:使用path來匹配路由,而後經過query來傳遞參數
這種狀況下 query傳遞的參數會顯示在url後面?id=?code

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

 對應路由配置:component

 {
     path: '/describe',
     name: 'Describe',
     component: Describe
   }

對應子組件: 這樣來獲取參數router

this.$route.query.id

 

這裏要特別注意 在子組件中 獲取參數的時候是$route.params 而不是
$router 這很重要~~~
相關文章
相關標籤/搜索