我刚刚开始使用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>
谢谢你的帮助 .
2 回答
好吧我终于发现查询中的数据是不可变的,这就是我无法更新它们的原因 .
解决方案是使用Object.assign或lodash cloneDeep创建一个新对象 .
你肯定是在正确的轨道上!我注意到的一件事是
Product
在你的JS中大写,但不在你的模板中 . 所以要么像这样更新你的模板:...或者在JS中使用
product
小写(我个人更喜欢) .另外,我认为在这种情况下你需要使用reactive parameters .
variables
将需要是一个函数而不是一个对象 .