英文:
Nuxt 3 and Vue 3 onMounted call function useFetch function not getting data form APIs
问题
你好,我是新手在Nuxt和Vue中。我正在使用Nuxt框架从API获取数据。我想在onMounted方法调用时从API获取数据。
我创建了一个单独的函数来调用API。该API根据产品ID获取数据。
如果我在没有onMounted方法的情况下调用API,它可以正常工作,但是当我在onMounted方法中调用函数时,它不起作用。始终获取“null”值。
以下是提供的代码:
<script setup>
const product = async (id) => {
const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);
console.log("after this" + id);
console.log(data.value);
};
onMounted(async () => {
product(2);
});
</script>
控制台输出
after this 2
null
英文:
Hi i am new in Nuxt and Vue. I am using Nuxt framework to get data form APIs. I want to get data from APIs when onMounted method call.
I created saprate function to call api. That api get data with product id.
If i call API without onMounted method it is working fine but when i call function in OnMounted method it is not working. always get "null" value.
Code given blew
<script setup>
const product = async (id) => {
const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);
console.log("after this" + id);
console.log(data.value);
};
onMounted(async () => {
product(2);
});
</script>
Otuput in console
after this 2
null
答案1
得分: 2
我不认为这是由于 onMounted
导致的,但似乎是一个时机问题。
使用以下方式的 nextTick
解决了这个问题:
import { nextTick } from 'vue';
onMounted(async () => {
await nextTick();
await getProduct(2);
});
我为您创建了一个可用的复现,供您测试 这里。
英文:
I don't think this is due to onMounted
but it seems to be a timing issue
Using nextTick
as follows solve the issue:
import { nextTick } from 'vue';
onMounted(async () => {
await nextTick();
await getProduct(2);
});
I created a working reproduction for you to test here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论