2017-08-24 85 views
0

我剛剛開始使用Apollo和Vue GraphQL,所以它可能是一個「愚蠢」的問題,但我不知道該怎麼做。GraphQL vue阿波羅查詢和突變相同視圖

我怎麼能同一個視圖內做一個查詢來獲取一個對象,並使用突變更新

比方說,我有一個簡單的模式

type Product { 
    id: ID! 
    title: String! 
    description: String 
} 

而一個VUE組件

<script> 

    // GraphQL query 
    const ProductQuery = gql ` 
    query($id: ID){ 
     Product(id: $id) 
     { 
     id 
     title 
     description 
     } 
    } 
    `; 

    const UpdateProductQuery = gql ` 
    mutation updateProduct($id: ID!, $title: String!, $description: String) { 
     updateProduct(
     id: $id, 
     title: $title, 
     description: $description, 
    ) { 
     id 
     } 
    } 
    `; 

export default { 
    data() { 
     return { 
     Product: {}, 
     }; 
    }, 
    apollo: { 
     Product: { 
      query: ProductQuery, 
      variables() { 
        id: 1234, 
      }; 
     }, 
    }, 
    methods: { 
     updateProduct() { 

      this.$apollo.mutate({ 
      mutation: UpdateProductQuery, 
      variables: { 
       id: this.Product.id, 
       title: this.Product.title, 
       description: this.Product.description, 
      }, 
      }) 
     } 
    } 
}; 
</script> 

現在我該如何編寫模板部分?我可以將產品對象鏈接到輸入內的V模型嗎?

<template> 
    <section> 
     <input v-model="product.title"></input> 
     <input v-model="product.description"></input> 
     <button @click="updateProduct">Update</button> 
    </section> 
</template> 

感謝您的幫助。

回答

0

好,我終於找到了從查詢數據是不可變的,這就是爲什麼我不能更新它們。

解決方案是使用Object.assign或lodash cloneDeep創建一個新對象。

0

你絕對是在正確的軌道上! 我注意到的一件事情是Product在您的JS中大寫,但不在您的模板中。所以,無論是更新您的模板,像這樣:

<template> 
    <section> 
    <input v-model="Product.title"></input> 
    <input v-model="Product.description"></input> 
    <button @click="updateProduct">Update</button> 
    </section> 
</template> 

......或使product小寫在你的JS(我個人比較喜歡)。

此外,我相信你需要在這種情況下使用reactive parametersvariables將需要是一個功能,而不是一個對象。

variables() { 
    return { 
    id: this.Product.id, 
    title: this.Product.title, 
    description: this.Product.description 
    } 
} 
+0

嘿,謝謝你的回覆。是的,我實際上已將其更改爲小寫。但是在我的updateProduct()方法中,'this.product'沒有新的值。不知道我是否做錯了 – Jerome

+0

@Jerome,我更新了我的答案。我認爲使用「反應參數」是關鍵。 – MattDionis