Skip to main content

Mutations

<script setup>
import { useMutation } from "@tanstack/vue-query";

const { isLoading, isError, error, isSuccess, mutate } = useMutation({
mutationFn: (newTodo) => axios.post("/todos", newTodo),
});

function addTodo() {
mutate({ id: new Date(), title: "Do Laundry" });
}
</script>

<template>
<span v-if="isLoading">正在添加待办事项...</span>
<span v-else-if="isError">发生错误:{{ error.message }}</span>
<span v-else-if="isSuccess">Todo已添加!</span>
<button @click="addTodo">创建Todo</button>
</template>
<script>
import { useMutation } from "@tanstack/vue-query";

const { error, mutate, reset } = useMutation({
mutationFn: (newTodo) => axios.post("/todos", newTodo),
});

function addTodo() {
mutate({ id: new Date(), title: "Do Laundry" });
}
</script>

<template>
<span v-else-if="error">
<span>发生错误:{{ error.message }}</span>
<button @click="reset">重置错误</button>
</span>
<button @click="addTodo">创建待办事项</button>
</template>
const client = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
});

// 我们需要一个默认的mutation函数 以便在页面重新加载后可以继续已暂停的mutations
queryClient.setMutationDefaults({
mutationKey: ["todos"],
mutationFn: ({ id, data }) => {
return api.updateTodo(id, data);
},
});

const vueQueryOptions: VueQueryPluginOptions = {
queryClient: client,
clientPersister: (queryClient) => {
return persistQueryClient({
queryClient,
persister: createSyncStoragePersister({ storage: localStorage }),
});
},
clientPersisterOnSuccess: (queryClient) => {
queryClient.resumePausedMutations();
},
};

createApp(App).use(VueQueryPlugin, vueQueryOptions).mount("#app");