簡體   English   中英

GraphQL vue阿波羅查詢和變異相同視圖

[英]GraphQL vue apollo query and mutation same view

我剛剛開始將GraphQL與Apollo和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>

現在我應該怎么寫模板部分? 我可以將Product對象鏈接到輸入中的v模型嗎?

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

謝謝你的幫助。

您絕對是在正確的軌道上! 我注意到的一件事是Product在您的JS中大寫,但在模板中不大寫。 因此,要么像這樣更新您的模板:

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

...或在JS中將product小寫(我個人更喜歡)。

另外,我相信您在這種情況下需要使用反應性參數 variables將需要是一個函數而不是一個對象。

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

好的,我終於發現查詢中的數據是不可變的,這就是為什么我無法更新它們。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM