我在Nuxt 3中有下面的异步可组合,它不像预期的那样工作,来自一个React背景,我想我遗漏了一些东西。
我的可组合代码中有以下代码。
// useAsyncFoo.js
export default () => {
const foo = ref(null);
someAsyncFn().then(value => foo.value = value);
return foo;
}
然后在我的页面上,我这样使用它:
<script setup>
const foo = useAsyncFoo();
console.log(foo); // null
</script>
...
我预计foo
将接受诺言返回的值,但它始终是null
。
在Nuxt 3 (await useAsyncFoo()
)中等待可组合性并将其导出为异步函数是很常见的吗?我做错什么了吗?
发布于 2022-10-18 12:59:34
我花了一个下午的时间试图将数据从一个可组合的页面传输到一个页面,但是我总是得到一些奇怪的或未定义的数据。读到这里的评论,我终于明白了我错过了什么,并设法做到了,所以谢谢!如果可以的话,这是我的文件。
(FetchWrapper是一个可组合的,受此文章启发的,所以我不必在每个请求中添加令牌,但它使用的是Nuxt $fetch方法。)
我的可合成
export const useFoo = () => {
const { fetchWrapper } = useFetchWrapper()
const bar = ref([])
const getApiData = async () => {
try {
bar.value = await fetchWrapper
.get(`${useRuntimeConfig().public.API_URL}/foobar`, null)
} catch(error) {
//
}
}
return { bar, getApiData }
}
我的页面
<script setup>
const { bar, getApiData } = useFoo()
await getApiData()
</script>
<template>
{{ bar }}
</template>
https://stackoverflow.com/questions/73985358
复制相似问题