使用Vue 2.2.6版本
我已经构建了非常简单的Vue实例,我希望它返回员工名称列表。但问题是获取/employees.json
employees
数据后没有更新。我尝试使用console.log调试它,它显示在loadData()
函数内部员工数据设置正确。但执行此功能后,员工价值再次变为空。
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
变量?
答案 0 :(得分:4)
console.log
中的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();
}
})
&#13;
<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>
&#13;