Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update component data after calling mounted function? [duplicate]

Tags:

vue.js

axios

I'm trying to update my component's data after calling an API (calling method from mounted function)

axios.get("getInfo")
    .then(function(res){
        this.result = res.data.result
        }).catch(function(err){
        console.log(err)
})

however the "this.result = res.data.result" doesn't get executed but when i paste the same line before the call, I get result updated (like this.data.result = 20). Also when I try the console.log(res.data) I get no response

I also get the message on the console that the request was completed

XHR finished loading: GET "http://app/getInfo".

My mounted function is like this

mounted:function(){
   this.setData()
}, 
methods:{
   setData:function(){
      console.log(this.pullData())
   },
}

What am I doing wrong? Thanks in advance

like image 405
Paco Meraz Avatar asked Dec 14 '22 19:12

Paco Meraz


1 Answers

You need to store the reference to the component in a variable firstly, then refer to it in the function with the variable instead of this keyword; The reason is that you created a new function in then, this thus refers to the function instead of the Vue component:

var ref = this;

axios.get("getInfo")
    .then(function(res){
        ref.result = res.data.result
//      ^^^ ref instead of this         
        }).catch(function(err){
        console.log(err)
})

And another more straight forward way to do this is to use arrow function which doesn't have a this context:

axios.get("getInfo").then(res => {     // arrow function instead of anonymous function
  this.result = res.data.result
}).catch(err => {
  console.log(err)
})
like image 178
Psidom Avatar answered Dec 16 '22 09:12

Psidom