【发布时间】:2022-11-11 11:25:07
【问题描述】:
如何使用 Composition Api 在 Vue3 中发生 graphql 突变后更新查询的缓存?我在 main.js 中有我的 vue 设置,如下所示:
import { createApp, provide, h } from "vue"
import App from "./App.vue"
import router from "./router";
import { InMemoryCache, HttpLink, ApolloClient } from "@apollo/client";
import { DefaultApolloClient } from '@vue/apollo-composable';
const apClient = new ApolloClient({
cache: new InMemoryCache({ addTypename: false }),
link: new HttpLink({ uri: 'http://localhost:8000/graphql' }),
});
const app =createApp({
setup() {
provide(DefaultApolloClient, apClient);
},
render: () => h(App),
});
app.use(router)
.mount('#app')
我的 graphql 查询如下所示:
query getMatters($id:ID, $client:ID) {
Matters(client:$client, id:$id) {
client {
id
name
}
category
id
title
status
}
}
结果如下所示:
{
"data": {
"Matters": [
{
"category": "Game",
"id": "2",
"title": "Clown and clown",
"status": "Open",
},
{
"category": "Players",
"id": "3",
"title": "Second thing",
"status": null,
},
{
"category": "Game",
"id": "4",
"title": "Jacks",
"status": "Open",
},
{
"category": "Game",
"id": "5",
"title": "aaa",
"status": null,
},
"category": "Game",
"id": "6",
"title": "fff",
"status": null,
}
]
}
}
删除突变
mutation deleteMatter($input:[MatterUpdate] ){
DeleteMatter(input: $input) {
success
errors
}
}
此处的删除功能有效,但我尝试更新缓存:
const { mutate: deleteResult } = useMutation(deleteMatter, () =>({
variables: {"input": {"id": matter.value.id},
}, update: (cache) => {
cache.evict({ id: cache.identify({ __typename: 'Matter', id: matter.value.id }) });
cache.gc();
},
}))
但它没有在浏览器中刷新。我也试过:
const { mutate: deleteResult } = useMutation(deleteMatter, () =>({
variables: {"input": {"id": matter.value.id},
}, update: (cache) => {
let data = cache.readQuery({query: getMatters, variables: {
client: id.value}})
const matterlist = data.matters.filter((t) => (t.id !== matter.value.id))
cache.writeQuery({query: getMatters, data: {matters: matterlist}})
}
}))
但出现错误Uncaught (in promise) Error: data.matters is undefined
也试过:
deleteResult({"input": {"id": matter.value.id},
}, {update: (cache) => {
let data = cache.readQuery({query: getMatters, variables: {
client: id.value}})
const currentItem = data.Matters.find(item => item.id === matter.value.id)
data.Matters.splice(data.Matters.indexOf(currentItem), 1);
cache.writeQuery({query: getMatters, data, variables:{client: id.value}})
}})
但是得到了错误Uncaught (in promise) Error: property 2 is non-configurable and can't be deleted
【问题讨论】:
标签: browser-cache vue-composition-api vue-apollo graphql-mutation