iskvmk
iskvmk

Reputation: 392

Why data of the Vue instance is not updated

Vue 2.2.6 version is used.
I have built very simple Vue instance and I want it to return the list of employees names. But the problem is that after getting /employees.json employees data is not being updated. I tried to debug it with console.log and it shows that inside loadData() function employees data is set correctly. But after this function is executed employees value becomes empty again.

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
  }
})

Where am I wrong? How correctly assign value from /employees.json to employees variable?

Upvotes: 1

Views: 580

Answers (1)

Roy J
Roy J

Reputation: 43899

The console.log in mounted will return empty because the loadData is asynchronous, and will not have completed.

Your el isn't going to work because it needs a #: '#employees' The template isn't going to work inline like that, because templates are for components. Where would it put it?

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>

Upvotes: 4

Related Questions