Vue.JS - Api request - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'quote')
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>
我正在尝试从 Directus 项目中随机获取报价 API。
但是这段代码一直给我错误 :
Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading 'quote').
我已经尝试了几种不同的解决方案,但现在我被卡住了,需要帮助找出阻止此代码工作的原因。
任何帮助将不胜感激。
问题是,您试图在获取 fetchedQuotes.data.quote
之前访问它。要处理此问题,请检查 fetchedQuotes
在 html 标签
中是否不为空
<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>
<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').
我已经尝试了几种不同的解决方案,但现在我被卡住了,需要帮助找出阻止此代码工作的原因。
任何帮助将不胜感激。
问题是,您试图在获取 fetchedQuotes.data.quote
之前访问它。要处理此问题,请检查 fetchedQuotes
在 html 标签
<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>