我有选项 API 组件:
export default defineComponent({
name: "mycomponent",
async setup() {
console.log(await useFetch('http://localhost/api/data'));
},
})
当我尝试运行此代码 Nuxt3 时出现错误:
500
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at `https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables`.
错误表示我必须从 Vue 设置函数调用此可组合项,但我已经从设置函数调用此可组合项。有什么问题吗?
尝试使用以下代码:
导出默认的defineComponent({ 名称:“我的组件”, 异步设置() { const nuxtApp = useNuxtApp() 等待 callWithNuxt( nuxt应用程序, 异步()=> { console.log(等待 useFetch('http://localhost/api/data'))); } ); } });
作为参考,我发现在以下问题中使用 pi0 的 awnser 解决了尝试在没有 nuxt 实例可用的情况下使用 useFetch 时的大部分问题。