【问题标题】:Avoid caching problems when creating an edit form with vue-apollo使用 vue-apollo 创建编辑表单时避免缓存问题
【发布时间】:2020-07-18 21:50:56
【问题描述】:

我正在处理我的第一个 vue-apollo 项目,我想知道创建编辑表单的最佳方法是什么。我似乎在网上找不到任何示例。

现在我正在像这样查询我的用户数据:

export default {
  data() {
    return {
      user: {
        id: '',
        name: '',
        email: '',
      },
    }
  },
  apollo: {
    user: {
      query: USER_QUERY,
    },
  },
}

用这样一个简单的形式:

<form @submit.prevent="submitForm">
  <label>Name</label>
  <input type="text" v-model="user.name" />

  <label>Email</label>
  <input type="text" v-model="user.email" />

  <button type="submit">Submit</button>
  <button type="button" @click="cancel">Cancel</button>
</form>

问题是当我编辑表单然后关闭它时,当我返回表单时,GraphQL 缓存会返回我的编辑。这是因为我的输入直接绑定到使用 v-model 的 GraphQL 查询返回的对象。我可以想到两件事来避免这种情况:

  • 创建查询返回的数据的副本(并将其称为 user 和 userData?),并将 v-model 绑定到该对象的键。但让我感到困扰的是,我需要创建一个重复的变量并将数据放在两个地方。
  • 或者完全禁用此 GraphQL 查询的缓存。

感觉好像我错过了一个更明显的解决方案。当我使用 REST 时,有一个 Form 类基于此处理所有表单交互:

https://medium.com/@jeffochoa/vuejs-laravel-object-oriented-forms-f971cb50b7ab

也许可以用类似的方式解决?使用 Vue/Apollo/GraphQL 构建(编辑)表单的首选方法是什么?

【问题讨论】:

    标签: vue.js graphql vue-apollo


    【解决方案1】:

    我只能告诉你我喜欢的方式。在最基本的情况下,我会做这样的事情......

    UserForm.vue

    <template>
    <form @submit.prevent="submitForm">
      <label>Name</label>
      <input type="text" v-model="proposedName" />
    
      <button type="submit">Submit</button>
      <button type="button" @click="cancel">Cancel</button>
    </form>
    </template>
    
    <script>
    import MyUserQuery from '/wherever/MyUserQuery.gql'
    import MyUserMutation from '/wherever/MyUserMutation.gql'
    
    export default {
      data() {
        return: {
          proposedName: ''
        }
      },
    
      methods: {
        submitForm() {
          this.$apollo.mutate({
            mutation: MyUserMutation,
            variables: {
              name: this.proposedName
            }
          })
    
          this.proposedName = ''
        }
      },
    
      apollo: {
        user: {
          query: MyUserQuery,
          result({data}) {
            this.proposedName = data.user.name
          }
        }
      }
    }
    </script>
    

    我的proposedVariable 内容很冗长,但我发现它使我不会混淆表单数据和 Apollo 数据。我敢肯定其他人有其他策略。

    【讨论】:

    • 谢谢,我最终选择了类似的方法!
    【解决方案2】:

    Javascript 对象存储为reference。当您将对象分配给另一个变量时,您只是将对象的内存地址分配给该变量。

    因此,在结果对象中,您应该避免直接赋值并使用 JSON.parse 之类的:

    this.proposedName = JSON.parse(JSON.stringify(data.user.name))
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2011-09-25
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 2020-07-07
      • 1970-01-01
      相关资源
      最近更新 更多