我正在創建一個靜態站點@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,還有其他方法可以實作這種行為嗎?
謝謝!
uj5u.com熱心網友回復:
在此處查看檔案。從外觀上看,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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/328308.html
下一篇:從VueJS中的URL獲取引數
