[英]Vue.JS - Api request - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '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>
I am trying to randomly fetch quotes from a Directus project API.我正在尝试从 Directus 项目 API 中随机获取报价。 But this code keeps giving me the error :
但是这段代码一直给我错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'quote').
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'quote')。
I have tried several different solutions but now I am stuck and need help figuring out what's preventing this code from working.我尝试了几种不同的解决方案,但现在我被困住了,需要帮助找出阻止此代码工作的原因。
Any help will be appreciated.任何帮助将不胜感激。
The problem is, you are trying to access fetchedQuotes.data.quote
before its being fetched.问题是,您正试图在获取
fetchedQuotes.data.quote
之前访问它。 To handle this, check if your fetchedQuotes
is not empty in your html tag要处理此问题,请检查您的
fetchedQuotes
在您的 html 标记中是否为空
<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.