hahaha
hahaha

Reputation: 1389

How can I assign data from received data in VueJS?

How can I assign data from received data? my code is below. axios is working well. I can get response.data from server . and I tried to assign the data to imglists variable. but It doesn't assign. What's wrong with me? Is There something wrong? please help me out.

var app = new Vue({
  el: '#app',  
  data: {      
    imglists: [],  
  },  
  created(){     
      axios.post('https://test.com/hello-lambda')
   .then(function (response) {        
     this.imglists = response.data;
   }).catch(function (error) {    
    console.log(error);  
   });  
}})

Upvotes: 1

Views: 85

Answers (2)

Marc
Marc

Reputation: 5465

Your reference to this is scoped to the function it is inside of so you need to create an external reference.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Also data should be a returned object to create a reactive object to trigger re-renders (nextTick) when the data is changed in imagelists due to this usage case being an asynchronous call.

https://v2.vuejs.org/v2/guide/reactivity.html#Async-Update-Queue

var app = new Vue({

  el: '#app',

  data: () => ({
    imglists: []
  }),

  created(){

    let self = this;

    axios.post('https://test.com/hello-lambda').then(response => {  
  
        self.imglists = response.data;

   }).catch(error => {    
     console.log(error);  
   });  

}})

The var self and function then() plus its own content is scoped to function created() allowing child functions access to vars declared at the top level (parent function or script file) but be mindful if 'strict mode' is enforced as this will change the behavior of scoping / inheritance.

Upvotes: 1

Jon Awoyele
Jon Awoyele

Reputation: 356

In the example code above this is bound to the created function. To bind this to the object context, you'll need a function that doesn't bind this. Use ES6(ES2015) to solve the binding issue.

Use the ES6 syntax:

var app = new Vue({
  el: '#app',  
  data: {      
    imglists: [],  
  },  
  created(){     
      axios.post('https://test.com/hello-lambda')
       .then(response =>  this.imglists = response.data)
       .catch(error =>console.log(error));  
  }
})

Upvotes: 1

Related Questions