vue.js并未传递所有数据

时间:2018-02-10 19:18:55

标签: vue.js axios

晚上好,我正在使用axios检索数据,当我在控制台登录时,我看到它已成功检索到。当我将数据传递给我的组件时,数据以某种方式不满。它只显示从第一个axios.get(会话但没有消息)检索到的数据,但是当我使用vue.js调试工具检查它时,我可以看到该对象具有来自服务器的所有数据。不知道哪里出错了。

app.js

 const app = new Vue({
    el: '#app',
    data: {
        conversations: {
            list: [],
            current: {
                messages: []
            }
        }
    },
    created() {
        axios.get('/conversations').then(response => {
            this.conversations.current = response.data[0];
        });

        axios.get('/messages').then(response => {
            this.conversations.current.messages = response.data;
            console.log(this.conversations.current);
            /* this console.log prints the json with 25 messages in it */
        });
    }
});

index.blade.php

<div class="list-group">
   <div class="list-group-item active">Messages</div>
   <chat-log :conversations="conversations"></chat-log>
</div>

聊天log.vue

<template lang="html">
    <div class="chat-log pre-scrollable">
        <chat-message class="list-group-item" v-for="message in conversations.current.messages" :message="message"></chat-message>

        {{ conversations.current.messages }} // THIS IS EMPTY SOMEHOW
    </div>
</template>

<script>
    export default {
        props: ['conversations']
    }
</script>

在聊天消息组件中,我创建了一个方法,在单击时调用再次检索消息并再次将它们放入数组中,然后它们以某种方式出现但我不明白为什么它们不会出现在加载中。

2 个答案:

答案 0 :(得分:2)

除非与Promise一起使用,否则您无法保证这些异步调用将按顺序返回:

Promise.all([
    axios.get('/conversations'),
    axios.get('/messages')
]).then(values => {
    this.conversations.current = values[0]
    this.conversations.current.messages = values[1]
})

Promise.all()

  

Promise.all等待所有履行(或第一次拒绝)

此外,您的data财产不具有被动性。它必须声明为函数:

data () {
    return {
        conversations: {
            list: [],
            current: {
                messages: []
            }
        }
    }
}

答案 1 :(得分:0)

无法保证您的对话&#39;端点将在“消息”之前解决。端点。尝试在承诺链中构建它,或者如@btl建议的那样,使用promise.all()

new Vue({
    el: '#app',
    data: function() {
        return {
            conversations: {
                list: [],
                current: {
                    messages: []
                }
            }
        }
    },
    created() {
        return Promise.all([
            axios.get('/conversations'),
            axios.get('/messages')
        ])
        .then(reply => {
            this.conversations.current = reply.data[0];
            this.conversations.current.messages = reply.data[1];
        });
    }
});