2017-02-27 16 views
1

的問題後更新。

我有下列數據的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> 

當最初安裝,既conversationscurrentConversation爲空。顯示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沒有。

+0

我沒有看太深入的問題,但我認爲這不是'v-for'問題,我認爲這與嵌套有關。如果你的數據超過2維,你會得到我認爲的錯誤。 (我暫時用'v-if'解決了我的問題,就像你一樣) – Traxo

+0

@Traxo我最初認爲這可能是一個奇怪的問題,但我不明白這兩個模板的深度相同獲取數據,但只有一個有問題。 v-if的問題是我不應該用一個模板來做,而是不要用另一個模板來做。 – joexanderson

+0

你說「currentConversation拋出以下錯誤」,但我沒有看到'.users'在那裏? – Traxo

回答

1

問題是什麼?

您初始化您的currentConversation財產與null

I have a Vue component with the following data:

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

+0

問題是我不必使用空數組及其任何嵌套屬性來初始化對話。但通過currentConversation,我確實。當他們做同樣的事情時,爲什麼我會遇到一個問題,而不是另一個問題? – joexanderson

+1

@joexanderson不一樣,在currentConversation的情況下,你試圖獲取它的屬性,例如null.messages,而在第一種情況下,你只是試圖迭代null,這與vue很好。 – Traxo

+1

@Traxo好吧,我現在明白了。感謝您的幫助,我非常感謝! – joexanderson

3
currentConversation: {}, 

insted的的

currentConversation: null, 
+0

好的,所以使用空數組進行初始化。但是,我不明白爲什麼我必須爲currentConversation設置一個空數組,但不要用於對話。 – joexanderson