2017-08-20 63 views
0

如何在我的組件方法中通過ajax循環數據集?問題是,當我嘗試調用一個方法在組件mounted()上執行循環時,數據還沒有。我如何告訴我的vue組件等待ajax數據到達以執行該功能?在子組件中循環使用父數據(通過Ajax設置)

Vue.component('sidebar', { 
 
    props: ['people'], 
 
    template: ` 
 
     <div id="sidebarContain" v-if="this.people"> 
 
      <div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id"> 
 
       {{person.first_name + ' ' + person.last_name}} 
 
      </div> 
 
     </div> 
 
    `, 
 
    methods: { 
 
    isCheckedIn(person) { 
 
     return person.reg_scan == null ? true : false; 
 
    }, 
 
    displayName() { //this is the function I want to run when ajax data is done and passed from parent to child 
 
     for (var i = 0; i < this.people.length; i++) { 
 
     console.log(this.people[i]); 
 
     } 
 
    } 
 
    }, 
 
    mounted() { 
 
    this.displayName(); 
 
    } 
 
}); 
 

 
var app = new Vue({ 
 
    el: '#main', 
 
    data: { 
 
    people: [] 
 
    }, 
 
    methods: { 
 
    loadPeople() { 
 
     $.ajax({ 
 
     method: 'POST', 
 
     dataType: 'json', 
 
     url: base_url + 'users/getParticipants/' + event_id 
 
     }).done(data => { 
 
     this.people = data; 
 
     }); 
 
    }, 
 
    setRefresh() { 
 
     setInterval(() => { 
 
     console.log("Getting People"); 
 
     this.loadPeople(); 
 
     }, 10000); 
 
    } 
 
    }, 
 
    mounted() { 
 
    this.loadPeople(); 
 
    this.setRefresh(); 
 
    } 
 
});
<div id="app"> 
 
    <sidebar :people="people"></sidebar> 
 
</div>

回答

0

您可以設置人民陣列上的守望者,並呼籲觀察者的顯示名功能。每當人員數組中的數據發生變化時,觀察者都會運行,所以當ajax請求從API返回數據時,它將運行。另一個選擇是在回調中立即運行循環。