N
Nuxt3mo ago
dayo_Li

useFetch中的 参数为什么是空的?

const {data, refresh: getAddAccount }= GetFetchApi('/manage/admin/add',{ lazy:true, server:false, immediate: false, body: { account: user.account, password: user.password, name: user.name, admin_position_id: user.admin_position_id }, method:'POST', title:'添加用户成功', failtitle:'添加用户失败' }) <UButton v-if="title == '添加用户'" class="px-5" type="submit" @click="getAddAccount"> 添加 </UButton>
2 Replies
kapa.ai
kapa.ai3mo ago
Hi @dayo_Li. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- 在 Nuxt 3 中,useFetch 的参数(如 body)如果出现“空的”或未按预期传递,常见原因是你传递了响应式(reactive)对象(如 refreactive)作为 body,而不是普通的对象。这样做会导致每当 body 里的属性发生变化时,useFetch 会自动重新发送请求,甚至可能导致参数丢失或行为异常。 解决方法: - 如果你传递的是响应式对象,建议在传递给 body 时使用 JSON.stringify() 或解包为普通对象,避免响应式追踪。例如:
const { data, refresh: getAddAccount } = useFetch('/manage/admin/add', {
lazy: true,
server: false,
immediate: false,
body: JSON.parse(JSON.stringify({
account: user.account,
password: user.password,
name: user.name,
admin_position_id: user.admin_position_id
})),
method: 'POST'
})
const { data, refresh: getAddAccount } = useFetch('/manage/admin/add', {
lazy: true,
server: false,
immediate: false,
body: JSON.parse(JSON.stringify({
account: user.account,
password: user.password,
name: user.name,
admin_position_id: user.admin_position_id
})),
method: 'POST'
})
或者直接传递一个普通对象(确保 user 的属性不是 ref 或 reactive):
body: {
account: user.account,
password: user.password,
name: user.name,
admin_position_id: user.admin_position_id
}
body: {
account: user.account,
password: user.password,
name: user.name,
admin_position_id: user.admin_position_id
}
参考说明: 有开发者遇到类似问题,原因正是“发送了响应式属性到 useFetch 的 body,每次属性变化都会重新请求”,用 JSON.stringify(body) 解决了问题【见此说明】(Stack Overflow: Multiple API requests sent from Pinia store Part 3)。 注意: - useFetch 的参数如 body 支持普通对象、ref、computed,但如果传递响应式对象,需确保不会被意外追踪和触发多次请求【官方文档说明】(useFetch - Parameters)。 - 你自定义的 titlefailtitle 不是 useFetch 的标准参数,useFetch 不会处理这些参数。 总结: 请确保传递给 body 的是普通对象,避免响应式对象带来的副作用。如果参数依然为空,请检查 user 的属性是否为 ref/reactive,并在传递时解包或序列化。 ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1410870997061603339> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?