簡體   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