javascript - Vue.JS 嵌套 v-for 抛出 null/未定义错误

标签 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

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

我发现如果我结束当前对话 <template>在另一个divv-if="currentConversation"指令,错误不会显示,并且模板可以正确呈现。但是,因为我不必使用 v-if破解对话<template> ,为什么我需要在当前对话中使用它 <template>

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

最佳答案

currentConversation: {},

已安装

currentConversation: null,

关于javascript - Vue.JS 嵌套 v-for 抛出 null/未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488324/

相关文章:

javascript - 如何 "refresh"单页应用程序

laravel - Vue SPA 网址在启用历史模式的情况下不起作用

javascript - Highcharts 圆形百分比图

javascript - 在图像 map 上的鼠标悬停时使用音频

javascript - apollo-client 没有响应头

javascript - 如何在 nuxt 中使用 google recaptcha?

javascript - 如何在 Laravel 项目中为 VueJS 3 设置 compilerOptions.isCustomElement

javascript - React 路由器动画在 browserify 后获取意外 token

javascript - 如何使用 ActionScript 从 Flash 动态包含 JavaScript?

javascript - "Missing )"错误