如何在Nuxt 3中使用onMounted执行异步操作。

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

how to use onMounted to do async things in Nuxt 3

问题

I don't know what's wrong with this, the repository ref's value just don't get updated

我不知道这有什么问题,repository 引用的值就是没有被更新

I wrote async/await, but it seems not working. repository is an empty array.

我使用了 async/await,但似乎不起作用。repository 是一个空数组。

I can use the api out of onMounted, so I think its something wrong about it. I don't know much about it.

我可以在 onMounted 外部使用 API,所以我认为问题可能出在这里。我对此不太了解。

Here's my code:

这是我的代码:

<template>
  <div>
    <h1>Starred Repositories</h1>
    <ul>
      <li v-for="repository in repositories" :key="repository.id">
        <h3>{{ repository.name }}</h3>
        <p>{{ repository.description }}</p>
      </li>
    </ul>
    <button @click="nextPage" :disabled="isLastPage">Next Page</button>
  </div>
</template>

<script setup>
import { Octokit } from '@octokit/core';

const repositories = ref([]);
const page = ref("1")
const runtimeConfig = useRuntimeConfig();

const octokit = new Octokit({
  auth: runtimeConfig.githubToken,
});

const nextPage = () => {
  page.value++;
}

onMounted(async () => {
  const response = await octokit.request('GET /user/starred?page=' + page.value, {
    headers: {
      'X-GitHub-Api-Version': '2022-11-28',
    },
  });
  repositories.value = response.data;
})

console.log(repositories.value);
</script>

also here's my app.vue:

还有我的 app.vue:

<script>
import Star from './components/Star.vue';

export default {
  components: {
    Star,
    }
}
</script>

<template>
  <Star />
</template>

Note: I've provided the translations for the code sections as requested.

英文:

I don't know what's wrong with this, the repository ref's value just don't get updated

I wrote async/await, but it seems not working. repository is an empty array.

I can use the api out of onMounted, so I think its something wrong about it. I don't know much about it.

Here's my code:

&lt;template&gt;
  &lt;div&gt;
    &lt;h1&gt;Starred Repositories&lt;/h1&gt;
    &lt;ul&gt;
      &lt;li v-for=&quot;repository in repositories&quot; :key=&quot;repository.id&quot;&gt;
        &lt;h3&gt;{{ repository.name }}&lt;/h3&gt;
        &lt;p&gt;{{ repository.description }}&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
    &lt;button @click=&quot;nextPage&quot; :disabled=&quot;isLastPage&quot;&gt;Next Page&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script setup&gt;
import { Octokit } from &#39;@octokit/core&#39;;

const repositories = ref([]);
const page = ref(&quot;1&quot;)
const runtimeConfig = useRuntimeConfig();

const octokit = new Octokit({
  auth: runtimeConfig.githubToken,
});

const nextPage = () =&gt; {
  page.value++;
}

onMounted(async () =&gt; {
  const response = await octokit.request(&#39;GET /user/starred?page=&#39; + page.value, {
    headers: {
      &#39;X-GitHub-Api-Version&#39;: &#39;2022-11-28&#39;,
    },
  });
  repositories.value = response.data;
})

console.log(repositories.value);
&lt;/script&gt;

also here's my app.vue:

&lt;script&gt;
import Star from &#39;./components/Star.vue&#39;

export default {
  components: {
    Star,
    }
}
&lt;/script&gt;

&lt;template&gt;
  &lt;Star /&gt;
&lt;/template&gt;

答案1

得分: 0

以下是您要翻译的内容:

"Your console log will execute and log an empty array because it will be executed before the code in onMounted, it is a hook and hooks don't themselves honour an async.

Move your console.log so it is inside the onMounted hook and also make sure the endpoint is infact retuning something other than an empty array it's self.


On a side note, using a life cycle hook for triggering API calls is not the best way, instead use the Top Level Await & Watch strategy.

https://nuxt.com/docs/getting-started/data-fetching#watch

In your case you are not using Nuxt's fetch helpers... so manual rigging looks like this:

&lt;script setup&gt;

import { Octokit } from '@octokit/core';

const repositories = ref([]);
const page = ref(1)
const runtimeConfig = useRuntimeConfig();

const octokit = new Octokit({
  auth: runtimeConfig.githubToken,
});

const nextPage = () =&gt; {
  page.value++;
}


const fetchStarredUsers = async (page) =&gt; {
  const response = await octokit.request(`GET /user/starred?page=${page}`, {
    headers: {
      'X-GitHub-Api-Version': '2022-11-28',
    },
  });

  if(Array.isArray(response?.data)) {
    repositories.value = response.data
    return
  }
  
  console.error('Invalid response, expected array of users').
}

// Call on entering component, (triggers loading suspense)
// https://nuxt.com/docs/getting-started/data-fetching#suspense
await fetchStarredUsers(page.value)

// Call on page being changed
watch(page, fetchStarredUsers)

</script>
英文:

Your console log will execute and log an empty array because it will be executed before the code in onMounted, it is a hook and hooks don't themselves honour an async.

Move your console.log so it is inside the onMounted hook and also make sure the endpoint is infact retuning something other than an empty array it's self.


On a side note, using a life cycle hook for triggering API calls is not the best way, instead use the Top Level Await & Watch strategy.

https://nuxt.com/docs/getting-started/data-fetching#watch

In your case you are not using Nuxt's fetch helpers... so manual rigging looks like this:

&lt;script setup&gt;

import { Octokit } from &#39;@octokit/core&#39;;

const repositories = ref([]);
const page = ref(1)
const runtimeConfig = useRuntimeConfig();

const octokit = new Octokit({
  auth: runtimeConfig.githubToken,
});

const nextPage = () =&gt; {
  page.value++;
}


const fetchStarredUsers = async (page) =&gt; {
  const response = await octokit.request(`GET /user/starred?page=${page}`, {
    headers: {
      &#39;X-GitHub-Api-Version&#39;: &#39;2022-11-28&#39;,
    },
  });

  if(Array.isArray(response?.data)) {
    repositories.value = response.data
    return
  }
  
  console.error(&#39;Invalid response, expected array of users&#39;).
}

// Call on entering component, (triggers loading suspense)
// https://nuxt.com/docs/getting-started/data-fetching#suspense
await fetchStarredUsers(page.value)

// Call on page being changed
watch(page, fetchStarredUsers)

&lt;/script&gt;

huangapple
  • 本文由 发表于 2023年6月18日 21:12:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500716.html
匿名

发表评论

匿名网友

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

确定