在组件的 `fetch` 方法中使用 axios 和 `nuxt/content`
Use axios together with `nuxt/content` in a component's `fetch` method
我正在使用 @nuxt/content
创建一个静态站点,并且我正在尝试创建一些将从降价中使用的组件。其中一个组件需要调用外部 API 来检索 HTML.
中显示的一些数据
这些是相关的片段,试图显示一张包含来自 GitHub 存储库的信息的卡片:
blog_article.md
In <content-github-repository repo="jgsogo/qt-opengl-cube">this repository</content-github-repository> there is...
content/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
的文档,还有其他方法可以实现这种行为吗?
谢谢!
查看文档 here。从外观上看,Nuxt 可以在 before 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>
我正在使用 @nuxt/content
创建一个静态站点,并且我正在尝试创建一些将从降价中使用的组件。其中一个组件需要调用外部 API 来检索 HTML.
这些是相关的片段,试图显示一张包含来自 GitHub 存储库的信息的卡片:
blog_article.md
In <content-github-repository repo="jgsogo/qt-opengl-cube">this repository</content-github-repository> there is...
content/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
的文档,还有其他方法可以实现这种行为吗?
谢谢!
查看文档 here。从外观上看,Nuxt 可以在 before 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>