<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 (reading 'quote')。
我嘗試了幾種不同的解決方案,但現在我被困住了,需要幫助找出阻止此代碼作業的原因。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
問題是,您正試圖在獲取fetchedQuotes.data.quote之前訪問它。要處理此問題,請檢查fetchedQuotes您的 html 標記中是否為空
<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484183.html
