2017-07-14 23 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高兴地帮助,并坦率地说,我阅读文档并学习了新的东西,所以也要感谢你:) –