Vue.JS - API 请求 - 未捕获(承诺中) 类型错误:无法读取未定义的属性(读取"quote")


<template>
<article class="message is-warning">
<div class="message-header">
<span>Code Quotes</span>
</div>
<div class="message-body">
<span v-html="fetchedQuotes.data.quote"></span>
<span>{{fetchedQuotes.data.author}}</span> 
</div>
</article>
</template>
<script>
export default {
data(){
return {

fetchedQuotes: [],
contentUrl: "https://apiurl.tld/"
};
},
mounted() {
this.getQuotes(this.contentUrl, "quotes");

},
methods: {
async getQuotes(url, collection) {
try {

let response = await fetch(url + collection+"/"+Math.ceil(Math.random()*6));
this.fetchedQuotes = await response.json();
} catch (error) {
console.log(error);
}
}
}
};
</script>

我正试图从Directus项目API随机获取报价。但是这段代码一直给我错误:

Uncaught (in promise) TypeError: Cannot read properties of undefined(阅读' ").

我已经尝试了几种不同的解决方案,但现在我卡住了,需要帮助弄清楚是什么阻止了这段代码的工作。

任何帮助都将不胜感激。

问题是,您试图在获取fetchedQuotes.data.quote之前访问它。要处理此问题,请检查html标签

中的fetchedQuotes是否为空。
<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>

最新更新