Nuxt 3 具有那些令人惊叹的数据获取功能(例如:useFetch),但我遇到了一种情况,我需要在渲染时间之后发出请求(例如:从按钮调用并发送搜索词)。
据我所知,useFetch 不适用于客户端,这是我试图做的
<template>
<button @click="goSearch()">Search</button>
</template>
setup() {
const goSearch = async () => {
const { data } = await useFetch('search', () => $fetch('/api/search'));
console.log(data.value);
};
return { goSearch };
},
}
nuxt3是否提供内置函数来按需发出http请求(客户端官方http axios之类)?
$fetch 应该可以工作。该问题是一个小错误,现已修复。如果您遇到此错误,只需升级 nuxt/ohmyfetch lib
npx nuxi upgrade --force
更多这里: https://github.com/nuxt/framework/issues/2502#issuecomment-999783226
useFetch 与使用 $fetch 相同,这里为什么不简单地使用代码中已有的 fetch 呢?
const { data } = await $fetch('/api/search' );
我认为你的代码不仅仅是你甚至可以在客户端使用 useFetch 而是那样:
const { data } = await useFetch('/api/search')
您应该使用useFetch提供的刷新或执行功能。这是我的建议:
A。在您的模板中:
<template>
<button @click="refresh()">Search</button>
</template>
B.在你的脚本中:
setup() {
const { data, refresh } = await useFetch('search', () => $fetch('/api/search'));
return { data, refresh };
}
文档:Nuxt 数据获取