[英]How can I access this.$route from within vue-apollo?
我正在使用vue-apollo
和graphql-tag
構建GraphQL查詢。
如果我硬編碼我想要的ID,它可以工作,但我想將當前路徑ID作為變量傳遞給Vue Apollo。
工作 (硬編碼ID):
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: 'my-long-id-example'
}
}
}
但是,我無法做到這一點:
不起作用 (嘗試訪問此ID。路由獲取ID):
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: this.$route.params.id
}
}
}
我收到錯誤:
未捕獲的TypeError:無法讀取未定義的屬性'params'
有沒有辦法做到這一點?
編輯 :完整的腳本塊,以便更容易看到發生了什么:
<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>
閱讀vue-apollo的文檔 (參見“反應參數”部分),您可以使用this.propertyName
來使用vue反應屬性。 所以只需將路徑參數初始化為數據屬性,然后在這樣的apollo對象中使用它
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
}
}
}
}
}
雖然接受的答案對於海報的例子是正確的,但如果你使用簡單的查詢,它就比必要的復雜得多。
在這種情況下, this
不是組件實例,因此您無法訪問this.$route
apollo: {
Property: gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}
但是,您只需將其替換為函數,它就會像您期望的那樣工作。
apollo: {
Property () {
return gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}
}
無需設置額外的道具。
您不能像這樣訪問“this”對象:
variables: {
id: this.$route.params.id // Error here!
}
但你可以這樣:
variables () {
return {
id: this.$route.params.id // Works here!
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.