2017-03-22 51 views
0

我很喜歡vue的newm,我試圖將我的laravel項目的前端遷移到vue,但我遇到了問題,我試圖循環訪問數組提供的對象稱爲房間,併爲我的組件中的每個房間創建div,並將默認room_id設置爲房間的第一個ID。問題是什麼時候在dom(html)中訪問提供的名爲'room'的prop數組時,它完美地工作,但是在我的組件vue代碼中,它總是顯示爲undefined或empty 這是我的組件vue代碼:在vue.js組件上運行的道具

export default { 
    created() { 
     //this.loadMessages(this.room_id) 
     console.log(this.first_room) //undefined; 
     console.log(this.rooms) //empty array; 
    }, 
    props: ['rooms','first_room'], 
    computes:{ 
     myrooms: function(){ 
      return this.first_room; 
     } 
    }, 
    data() 
    { 
     return{ 
      messages: [], 
      newMessage: '', 
      room_id: 1 //for test purposes, this works, 
     } 
    }, 
    methods: { 
     loadMessages(id) 
     { 
      axios.get('/messages/'+id).then(response => { 
       this.messages = response.data; 
       console.log(response.data); 
      }); 

     } 
    } 
} 

組件HTML的重要組成部分

<div v-for="room in rooms"> 
    <div class="chat-user room"> 
     <div v-for="other in room.others"> 
      <img class="chat-avatar img-circle" :src="other.image" alt="image" >           
      <div class="chat-user-name"> 
       <a :href="'/user/' + other.id">{{ other.name}}</a> 
      </div> 
     </div> 
    </div> 
</div> 
//this all works, just for reference 

方法,其中i設置傳遞到支柱在我的主VUE實例

EDIT值:父實例CODE 哦,我不能顯得過於訪問室陣列傳遞,因爲它總是空的代碼,但它在HTML環

window.App.app= new Vue({ 
el: '#wrapper', 
data: { 
    messages: [], 
    rooms: [], 
    test: 'yes', 
    first: '' 
}, 
created() { 
    this.fetchRooms(); 
    this.first = 1; 
}, 
methods: { 
    fetchMessages(id) { 
     console.log(id); 
    }, 
    fetchRooms() 
    { 
     axios.get('/rooms').then(response => { 
      this.rooms = response.data; 
     }); 
    } 
} 
}); 

終於在那裏我打電話給我的組件

<chat-messages :rooms="rooms" :first_room="1"></chat-messages> 
//variables referenced from main vue instance 

我有字面上把我的大部分頭髮都撕了這個,請大家幫助,謝謝

+0

你還可以添加父組件的vue-instance'代碼嗎? –

+3

這不是'計算',它應該'計算' –

+0

好吧@BelminBedak生病試試,謝謝 – carrion

回答

1

在道具傳遞的子元件中。

export default { 
    created() { 
    console.log(this.first_room) //undefined; 
    }, 
    props: ['rooms','first_room'], 
    computed :{ 
    myrooms: function(){ 
     return this.first_room; 
    } 
    }, 
    data() { 
    return { 
     messages: [], 
     newMessage: '', 
     room_id: 1 //for test purposes, this works, 
    } 
    }, 
    watch: { 
    rooms (n, o) { 
     console.log(n, o) // n is the new value, o is the old value. 
    } 
    }, 
    methods: { 
    loadMessages (id) { 
     axios.get('/messages/'+id).then(response => { 
      this.messages = response.data; 
      console.log(response.data); 
     }); 
    } 
    } 
} 

您可以在數據屬性上添加監視或計算以查看其值的更改。

在問題中(看起來是這種情況),您有 d道具的價值在created生命週期中,道具的值通過父組件中的API調用更改,在創建子組件。這就解釋了爲什麼您的模板顯示數據,但不在創建的生命週期鉤子中的console中。

+0

哇,非常感謝你解決了我的問題,正如你所說的,當房間第一次登錄時創建()它是空的,但是當他們登錄時,它包含所有的值,再次感謝! – carrion

+0

很高興幫助:) –