为什么不更新Vue实例的数据

时间:2017-04-06 19:46:48

标签: javascript vue.js vuejs2

使用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变量?

1 个答案:

答案 0 :(得分:4)

console.log中的mounted将返回空,因为loadData是异步的,并且不会完成。

您的el无法正常工作,因为它需要#:'#employees' template不会像这样内联工作,因为模板适用于组件。它会把它放在哪里?

&#13;
&#13;
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;
&#13;
&#13;