2017-04-06 54 views
1

使用Vue 2.2.6版本。
我已經構建了非常簡單的Vue實例,我希望它返回員工姓名列表。但問題是,得到/employees.jsonemployees數據沒有被更新。我試圖用console.log進行調試,它顯示loadData()函數員工數據設置正確。但是在這個函數被執行後,員工值再次變爲空。爲什麼不更新Vue實例的數據

var employees = new Vue({ 
    el: 'employees', 
    template: "<ul id='employees'><li v-for='employee in employees'>{{ employee['name'] }}</li></ul>", 
    data: { 
    employees: [] 
    }, 
    methods: { 
    loadData: function() { 
     this.$http.get('/employees.json').then(response => { 
     this.employees = response.body; 
     //1. console.log returns here ">employees: [object Object]" 
     }); 
    } 
    }, 
    mounted: function(){ 
    this.loadData(); 
    //2. console.log returns here empty employees value 
    } 
}) 

我在哪裏錯了?如何正確地將值從/employees.json分配到employees變量?

回答

4

console.log in mounted將返回空白,因爲loadData是異步的,並且不會完成。

el是行不通的,因爲它需要一個#:'#employees'template不會內聯這樣的工作,因爲模板是組件。它會放在哪裏?

var employees = new Vue({ 
 
    el: '#employees', 
 
    data: { 
 
    employees: [] 
 
    }, 
 
    methods: { 
 
    loadData: function() { 
 
     setTimeout(() => { 
 
     console.log('setting'); 
 
     this.employees = [{name:'one'},{name:'two'}]; 
 
     }, 800); 
 
     /*this.$http.get('/employees.json').then(response => { 
 
     this.employees = response.body; 
 
     //1. console.log returns here ">employees: [object Object]" 
 
     });*/ 
 
    } 
 
    }, 
 
    mounted: function(){ 
 
    this.loadData(); 
 
    } 
 
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script> 
 
<ul id='employees'><li v-for='employee in employees'>{{ employee['name'] }}</li></ul>

+0

謝謝您的回答!我將模板移至組件,現在它可以正常工作。 – iskvmk