2017-07-14 25 views
1

我在使用vue-apollographql-tag構建GraphQL查詢。

如果我硬編碼的ID我想,它的工作原理,但我想通過當前的路由ID Vue阿波羅作爲一個變量。

不工作(硬編碼ID):

apollo: { 
    Property: { 
     query: PropertyQuery, 
     loadingKey: 'loading', 
     variables: { 
     id: 'my-long-id-example' 
     } 
    } 
    } 

不過,我無法做到這一點:

不工作(試圖訪問的這個$路線。 ID):

apollo: { 
    Property: { 
     query: PropertyQuery, 
     loadingKey: 'loading', 
     variables: { 
     id: this.$route.params.id 
     } 
    } 
    } 

我得到的錯誤:

Uncaught TypeError: Cannot read property 'params' of undefined

有沒有辦法做到這一點?

編輯:全腳本塊,使其更容易地看到發生了什麼事情:

<script> 
import gql from 'graphql-tag' 

const PropertyQuery = gql` 
    query Property($id: ID!) { 
    Property(id: $id) { 
     id 
     slug 
     title 
     description 
     price 
     area 
     available 
     image 
     createdAt 
     user { 
     id 
     firstName 
     lastName 
     } 
    } 
    } 
` 

export default { 
    name: 'Property', 
    data() { 
    return { 
     title: 'Property', 
     property: {} 
    } 
    }, 
    apollo: { 
    Property: { 
     query: PropertyQuery, 
     loadingKey: 'loading', 
     variables: { 
     id: this.$route.params.id // Error here! 
     } 
    } 
    } 
} 
</script> 
+0

@VamsiKrishna感謝您的答覆。這是一個坐在默認導出上的對象。我更新了我的問題,以便在上下文中顯示。 –

回答

1

Readimg的documentation(見無功參數部分)VUE - 阿波羅您可以使用VUE反應特性通過this.propertyName 。因此,只要初始化路線PARAMS到data屬性然後用它在你阿波羅對象這樣

export default { 
    name: 'Property', 
    data() { 
    return { 
     title: 'Property', 
     property: {}, 
     routeParam: this.$route.params.id 
    } 
    }, 
    apollo: { 
    Property: { 
     query: PropertyQuery, 
     loadingKey: 'loading', 
     // Reactive parameters 
     variables() { 
     return{ 
      id: this.routeParam 
     } 
     } 
    } 
    } 
} 
+0

是的,這工作!謝謝。所以變量變成一個返回對象的函數,而不是直接作爲對象本身。謝謝! –

+1

@MichaelGiovanniPumo高興地幫助,並坦率地說,我閱讀文檔並學習了新的東西,所以也要感謝你:) –