1. 程式人生 > >Vue路由傳參的三種方式

Vue路由傳參的三種方式

現有如下場景,點選父元件的li元素跳轉到子元件中,並攜帶引數,便於子元件獲取資料。
父元件中:

<li v-for="article in articles" @click="getDescribe(article.id)">

方案一

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

對於此種方案,需要做如下的配置:

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

很顯然,需要在path中新增/:id來對應 $router.push 中path攜帶的引數,在子元件中可以使用來獲取傳遞的引數值。

this.$route.params.id

方案二

父元件中:通過路由屬性中的name來確定匹配的路由,通過params來傳遞引數。

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

對應路由配置: 注意這裡不能使用:/id來傳遞引數了,因為父元件中,已經使用params來攜帶引數。

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

子元件中: 子元件可以按照下面的方式來獲取引數:

this.$route.params.id

方案三

父元件:使用path來匹配路由,然後通過query來傳遞引數,這種情況下 query傳遞的引數會顯示在url後面?id=?。

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

對應路由配置如下:

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

子元件中: 子元件可以按照下面的方式來獲取引數:

this.$route.query.id