Vue.JS嵌套v-for抛出null / undefined错误

时间:2017-02-27 14:32:40

标签: javascript vue.js single-page-application axios

在问题结束时更新。

我有一个包含以下数据的Vue组件:

conversations: null,
currentConversation: null,

以及以下方法,该方法在mounted()上运行:

/**
 * Method to retrieve the user's conversations.
 */
getConversations() {
    axios.get('/api/user/conversations')
    .then((response) => {
        this.conversations = response.data;
    })
    .catch((error) => {
        console.log(error);
    })
},

<template>中,我使用以下内容显示每个会话:

<template v-for="conversation in conversations">
    <div class="conversation">
        <p>
            <!-- Template for each user -->
            <template v-for="(user, index) in conversation.users">
            {{ user.first_name }} {{ user.last_name }}<span v-if="index != (conversation.users.length - 1)">,</span>
            </template>
        </p>
    </div>
</template>

在当前对话的<template>中,我尝试使用以下内容:

<template v-for="message in currentConversation.messages">
    <div class="message">
        <div class="bubble">
            {{ message.content }}
        </div>
    </div>
</template>

最初安装时,conversationscurrentConversation均为空。显示conversations的模板工作正常。在Ajax请求返回数据之前它一直是空的。但是,currentConversation会引发以下错误:

Uncaught TypeError: Cannot read property 'messages' of null

当用户选择要查看的对话时,稍后将通过Ajax检索currentConversation对象。

我发现如果我使用<template>指令将当前对话div包装在另一个v-if="currentConversation"中,则错误不会显示,并且模板会正确呈现。但是,由于我不必在对话v-if上使用<template>黑客,为什么我需要在当前对话<template>上使用它?

更新:感谢@wing和@Traxo,使用空数组进行初始化是有效的。但是,我不明白为什么我必须最初为currentConversation设置一个空数组,但不要为conversations设置。

2 个答案:

答案 0 :(得分:3)

currentConversation: {},

insted of

currentConversation: null,

答案 1 :(得分:1)

有什么问题?

您使用currentConversation初始化null媒体资源。

  

我有一个包含以下数据的Vue组件:

conversations: null,
currentConversation: null,

v-for="message in currentConversation.messages"尝试迭代currentConversation.messages的可枚举属性。

currentConversation最初是null。因此

  

Uncaught TypeError: Cannot read property 'messages' of null

我该怎么办?

您可以使用空数组初始化currentConversation.messages

currentConversation: {
  messages: [],
},

这样,Vue可以尝试迭代currentConversation.messages,并清楚地表明currentConversation应该messages