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

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

Nuxt 3 and Vue 3 onMounted call function useFetch function not getting data form APIs

问题

  1. 你好,我是新手在NuxtVue中。我正在使用Nuxt框架从API获取数据。我想在onMounted方法调用时从API获取数据。
  2. 我创建了一个单独的函数来调用API。该API根据产品ID获取数据。
  3. 如果我在没有onMounted方法的情况下调用API,它可以正常工作,但是当我在onMounted方法中调用函数时,它不起作用。始终获取“null”值。
  4. 以下是提供的代码:
  5. <script setup>
  6. const product = async (id) => {
  7. const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);
  8. console.log("after this" + id);
  9. console.log(data.value);
  10. };
  11. onMounted(async () => {
  12. product(2);
  13. });
  14. </script>
  15. 控制台输出
  16. after this 2
  17. 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

  1. &lt;script setup&gt;
  2. const product = async (id) =&gt; {
  3. const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);
  4. console.log(&quot;after this&quot; + id);
  5. console.log(data.value);
  6. };
  7. onMounted(async () =&gt; {
  8. product(2);
  9. });
  10. &lt;/script&gt;
  11. Otuput in console
  12. after this 2
  13. null

答案1

得分: 2

我不认为这是由于 onMounted 导致的,但似乎是一个时机问题。

使用以下方式的 nextTick 解决了这个问题:

  1. import { nextTick } from 'vue';
  2. onMounted(async () => {
  3. await nextTick();
  4. await getProduct(2);
  5. });

我为您创建了一个可用的复现,供您测试 这里

英文:

I don't think this is due to onMounted but it seems to be a timing issue

Using nextTick as follows solve the issue:

  1. import { nextTick } from &#39;vue&#39;;
  2. onMounted(async () =&gt; {
  3. await nextTick();
  4. await getProduct(2);
  5. });

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:

确定