的問題後更新。
我有下列數據的Vue的組分:Vue.JS嵌套V-投擲空/未定義錯誤
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檢索。
我發現如果我用v-if="currentConversation"
指令將當前對話<template>
包裝在另一個div
中,則錯誤不會顯示出來,並且模板正確呈現。然而,由於我沒有使用上的談話<template>
的v-if
劈,我爲什麼要使用它在當前會話<template>
?
更新:感謝@wing和@Traxo,使用空數組進行初始化。不過,我不明白爲什麼我必須首先設置空數組currentConversation
,但conversations
沒有。
我沒有看太深入的問題,但我認爲這不是'v-for'問題,我認爲這與嵌套有關。如果你的數據超過2維,你會得到我認爲的錯誤。 (我暫時用'v-if'解決了我的問題,就像你一樣) – Traxo
@Traxo我最初認爲這可能是一個奇怪的問題,但我不明白這兩個模板的深度相同獲取數據,但只有一個有問題。 v-if的問題是我不應該用一個模板來做,而是不要用另一個模板來做。 – joexanderson
你說「currentConversation拋出以下錯誤」,但我沒有看到'.users'在那裏? – Traxo