我正在进行我的第一个vue-阿波罗项目,我想知道创建编辑表单的最佳方法是什么。我似乎在网上找不到任何例子。
现在,我正在像这样查询我的用户数据:
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模型的GraphQL查询返回的对象。我可以想到两件事来避免这种情况:
。
感觉好像我错过了一个更明显的解决方案。当我使用REST时,有一个表单类根据以下内容处理所有表单交互:
https://medium.com/@jeffochoa/vuejs-laravel-object-oriented-forms-f971cb50b7ab
也许可以用类似的方式解决?您最喜欢的使用Vue/阿波罗/GraphQL构建(编辑)表单的方法是什么?
发布于 2020-05-09 04:24:52
我只能告诉你我最喜欢的方式。最基本的是我会做这样的事..。
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是冗长的,但我发现它使我避免混淆表单数据和阿波罗数据。我相信其他人也有其他的策略。
发布于 2020-12-25 11:40:33
Javascript对象存储为引用。当您将对象赋值给另一个变量时,您只是将对象的内存地址分配给该变量。
因此,在
对象中,您应该避免直接赋值,并使用JSON.parse,例如:
this.proposedName = JSON.parse(JSON.stringify(data.user.name))https://stackoverflow.com/questions/61067578
复制相似问题