簡體   English   中英

如何從 Vue.js 中的方法返回數據?

[英]How to return data from method in Vue.js?

我正在學習 Vue.js,但找不到與此主題相關的任何內容。 我從 API 中獲取數據,該數據正確顯示在console.log ,但我似乎無法將其返回到模板視圖。 我不是要將此數據發送到另一個組件; 我想顯示它。 你如何做到這一點? 在 React 中,我會map結果並返回 HTML。 你如何在 Vue.js 中做到這一點? 另外,我在 Laravel 8 中這樣做。

<template>
    <div>
        {{ data }}
    </div>
</template>
<script>
    let api = location.search.replace("?", "/");
    api = api.replace("=", "");

    export default {
        name: "Play",
        data: function () {
            return {
                data: data
            };
        },
        created() {
            this.getQuestions();
        },
        methods: {
            getQuestions() {
                let data = [];
                fetch(api)
                    .then(response => response.json())
                    .then(response => {
                        return (data = response.results);
                    })
                    .catch(err => console.log(err));
            }
        }
    };
</script>

要訪問 Vue 組件上的data屬性,您必須使用this訪問器:

this.data = response.results

這里的數據是什么?

data: function() {
        return {
            data: *data*
        };
    },

此數據尚未在任何地方聲明,您需要將其設置為默認值,可能是這樣的 null,

data: function() {
        return {
            data: null
        };
    },

然后嘗試在這樣的方法中設置它

this.data = response.data

然后你可以像你已經做的那樣在模板中訪問它。

此外,建議使用 Vue 的 $set 方法來保持反應性流 - 所以你可以使用

this.$set(this, 'data', response.data);

來設置數據。

改變這個

 data: function() {
        return {
            data: data
        };
to 
 data: function() {
        return {
            data: null
        };

creataed()更改為mounted()

添加

this.data = response.results;

在你的 getQuestions() 代替你的return(data = response.results); 我想你也可以殺死.then(response => response.json())

在你的 vue 模板中你可以做

<div>
<template v-if="data"> {{data.somefield}}<template>
</div>

這個想法是您將數據設置為空,當組件安裝時,您“獲取”數據並將其保存到數據屬性。 Vue 看到數據不再為空並顯示 data.somefield

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM