目前,我在我的vue 3应用程序中使用vue-query by tanstack,代码结构如下。
我的todo/edit.vue中有以下代码
<template>
<v-container>
<v-row cols="12">
<v-text-field label="Name" v-model="formData.title"></v-text-field>
</v-row>
<v-row cols="12">
<v-text-field label="Price" v-model="formData.price"></v-text-field>
</v-row>
<v-row cols="12">
<v-col md="6" offset="6">
<v-btn color="success" @click="submit">Submit</v-btn>
</v-col>
</v-row>
</v-container>
</template>
<script setup lang="ts">
import { useQuery, useMutation, useQueryClient } from "@tanstack/vue-query"
import { fetchProduct, update} from "../services/product"
import { reactive } from "vue"
import { useRoute, useRouter } from "vue-router"
import type { IProduct } from "@/interface"
const route = useRoute()
let formData = reactive<IProduct>({
id: "",
title: "",
price: "",
category: "",
email: "",
})
const {
isLoading,
isError,
data: loadedData,
error,
refetch,
} = useQuery({
queryKey: ["getOneProduct", route.params.id],
queryFn: fetchProduct,
select: (data: any) => (formData = data),
})
const mutation = useMutation({
mutationFn: ({id, data}) => {
return update(id, data)
},
onSuccess: () => {
alert("success")
},
})
const submit = () => {
mutation.mutate({id:formData.id, data:formData})
}
</script>
我的services/product.ts
包含
import { API } from "../util/API"
import type { IProduct } from "../interface/IProduct"
export interface IProductsResponse {
products?: Array<IProduct>
total?: number
skip?: number
limit?: number
}
export const fetchProducts = async (): Promise<IProductsResponse> => {
return await API.get<IProductsResponse, any>(`/products?limit=10&select=id,title,price,category`)
}
export const fetchProduct = async (param: any): Promise<IProduct> => {
const id = param.queryKey[1]
const response = await API.get<IProduct, any>(`products/${id}`)
return response
// return await API.get<IProduct, any>(`/products/`)
}
export const update = async (id: any, data: any): Promise<IProduct> => {
return API.put(`/products/${id}`, data)
}
使用上面的代码设置,我得到以下错误:
类型“void”上不存在属性“id”。类型“void”上不存在属性“data”。
参考线:
mutationFn: ({id, data}) => {
return update(id, data)
},
和错误消息
类型“{ id:弦|数字;数据:联系我们|编号;标题:string; price:弦|数量;类别:字符串;电子邮件:“string; }; }”不能分配给类型为“void”的参数。
参考行:mutation.mutate({id:formData.id, data:formData})
使用“@tanstack/vue-query”执行PUT/PATCH操作的正确方法是什么?
1条答案
按热度按时间a0x5cqrl1#
在尝试这种情况时,我得到了同样的错误。帮助消除这个错误的是键入mutation函数的参数,所以在我的例子中,它是这样的:
但当我把它更新成这样:
错误消失了&函数按预期运行。希望这对您有帮助