2

我正在使用创建一个静态站点,@nuxt/content并且正在尝试创建一些将从降价中使用的组件。其中一个组件需要调用外部 API 来检索 HTML 中显示的一些数据。

这些是相关的片段,试图显示一张带有来自 GitHub 存储库的信息的卡片:

blog_article.md

In <content-github-repository repo="jgsogo/qt-opengl-cube">this repository</content-github-repository> there is...

内容/github/Repository.vue

<template>
  <span class="">
    <a :href="`https://github.com/${repo}`">
      <slot>{{ repo }}</slot>
    </a>
    <div>{{ info.description }}</div>
  </span>
</template>

<script>
export default {
  props: {
    repo: {
      type: String,
      require: true,
    },
  },
  data: () => ({
    info: null,
  }),
  async fetch() {
    console.log(`Getting data for repo: ${this.repo}`);
    this.info = (await this.$axios.get(`https://api.github.com/repos/${this.repo}`)).data;
  },
};
</script>

我得到的错误是Cannot read properties of null (reading 'description'),就像this.info在呈现 HTML 之前没有被填充......但它运行,因为我从 console.log 获得输出。也许我误解了有关的文档fetch,还有其他方法可以实现这种行为吗?

谢谢!

4

1 回答 1

2

在这里查看文档。从外观上看,Nuxt 可以在完成之前 fetch挂载组件,因此您需要防止data在组件中访问它时未设置它。

像下面这样简单的东西应该可以工作:

<template>
  <span class="">
    <a :href="`https://github.com/${repo}`">
      <slot>{{ repo }}</slot>
    </a>

    <p v-if="$fetchState.pending">Fetching info...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>{{ info.description }}</div>

  </span>
</template>
于 2021-10-20T00:04:46.217 回答