繁体   English   中英

Vue.JS - Api 请求 - 未捕获(承诺中)TypeError:无法读取未定义的属性(读取“报价”)

[英]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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM