GraphQL vue阿波罗查询和突变相同视图
问题描述:
我刚刚开始使用Apollo和Vue GraphQL,所以它可能是一个“愚蠢”的问题,但我不知道该怎么做。GraphQL 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>
现在我该如何编写模板部分?我可以将产品对象链接到输入内的V模型吗?
<template>
<section>
<input v-model="product.title"></input>
<input v-model="product.description"></input>
<button @click="updateProduct">Update</button>
</section>
</template>
感谢您的帮助。
答
好,我终于找到了从查询数据是不可变的,这就是为什么我不能更新它们。
解决方案是使用Object.assign或lodash cloneDeep创建一个新对象。
答
你绝对是在正确的轨道上! 我注意到的一件事情是Product
在您的JS中大写,但不在您的模板中。所以,无论是更新您的模板,像这样:
<template>
<section>
<input v-model="Product.title"></input>
<input v-model="Product.description"></input>
<button @click="updateProduct">Update</button>
</section>
</template>
......或使product
小写在你的JS(我个人比较喜欢)。
此外,我相信你需要在这种情况下使用reactive parameters。 variables
将需要是一个功能,而不是一个对象。
variables() {
return {
id: this.Product.id,
title: this.Product.title,
description: this.Product.description
}
}
嘿,谢谢你的回复。是的,我实际上已将其更改为小写。但是在我的updateProduct()方法中,'this.product'没有新的值。不知道我是否做错了 – Jerome
@Jerome,我更新了我的答案。我认为使用“反应参数”是关键。 – MattDionis