【发布时间】:2017-02-27 14:32:40
【问题描述】:
在问题结束时更新。
我有一个带有以下数据的 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
当用户选择要查看的对话时,稍后会通过 Ajax 检索 currentConversation 对象。
我发现,如果我使用 v-if="currentConversation" 指令将当前对话 <template> 包装在另一个 div 中,则不会出现错误,并且模板会正确呈现。但是,既然我不必在对话<template> 上使用v-if hack,为什么我需要在当前对话<template> 上使用它?
更新:感谢@wing 和@Traxo,使用空数组进行初始化是可行的。但是,我不明白为什么我必须为currentConversation 设置一个空数组,但不要为conversations 设置一个空数组。
【问题讨论】:
-
我并没有把问题看得太深,但我认为这不是
v-for的问题,我认为它与嵌套有关。如果您的数据超过二维,我认为您会收到该错误。 (我和你一样用v-if暂时解决了我的问题) -
@Traxo 我最初认为这可能是一些奇怪的问题,但我不明白当两个模板深入相同级别以获取数据时会发生什么,但只有一个有问题。
v-if的问题是我不应该使用一个模板而不是另一个模板。 -
您说“currentConversation 引发以下错误”,但我没有在其中看到
.users? -
@Traxo 我犯了一个错误,复制了错误的错误。它应该说
messages。更新的问题。
标签: javascript vue.js single-page-application axios