在问题结束时更新。
我有一个包含以下数据的 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>
最初安装时,conversations
和currentConversation
为空。显示conversations
的模板工作正常。在 Ajax 请求返回数据之前它是空的。然而,currentConversation
抛出以下错误:
Uncaught TypeError: Cannot read property 'messages' of null
currentConversation
当用户选择要查看的对话时,稍后会通过 Ajax 检索对象。
我发现如果我结束当前对话 <template>
在另一个div
与 v-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/