Nuxt 3 和 Vue 3 中的 onMounted 调用函数 useFetch 函数未从 API 中获取数据。

huangapple go评论99阅读模式
英文:

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

&lt;script setup&gt;

    const product = async (id) =&gt; {
      
       const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);
      
      console.log(&quot;after this&quot; + id);
      console.log(data.value);
      
   }; 

    onMounted(async () =&gt; { 
      product(2); 
      
    });
&lt;/script&gt;

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 &#39;vue&#39;;

onMounted(async () =&gt; {

  await nextTick();

  await getProduct(2);
});

I created a working reproduction for you to test here

huangapple
  • 本文由 发表于 2023年6月22日 04:59:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定