【问题标题】:GraphQL vue apollo query and mutation same viewGraphQL vue apollo 查询和变异同视图
【发布时间】:2018-02-01 19:37:26
【问题描述】:

我刚刚开始将 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-model 吗?

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

感谢您的帮助。

【问题讨论】:

    标签: vue.js vuejs2 graphql apollo vue-apollo


    【解决方案1】:

    好的,我终于发现查询中的数据是不可变的,这就是我无法更新它们的原因。

    解决方案是使用 Object.assign 或 lodash cloneDeep 创建一个新对象。

    【讨论】:

      【解决方案2】:

      您绝对是在正确的轨道上! 我注意到的一件事是 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 设为小写(我个人更喜欢)。

      另外,我相信在这种情况下您需要使用reactive parametersvariables 需要是一个函数而不是一个对象。

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

      【讨论】:

      • 您好,感谢您的回复。是的,我实际上将其更改为小写。但是在我的 updateProduct() 方法中,“this.product”没有新值。不确定我是否做错了什么
      • @Jerome,我更新了我的答案。我认为“反应式参数”的使用是关键。
      猜你喜欢
      • 2018-03-02
      • 2018-10-19
      • 2020-11-04
      • 2018-11-12
      • 2020-11-02
      • 2017-02-21
      • 2019-04-24
      • 2022-11-18
      • 2019-04-30
      相关资源
      最近更新 更多