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
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With