i have a simple form like so
<form @submit.prevent="getSummary">
<input type="text" v-model="userAcccount" placeholder="Enter Account
Number">
<button type="submit" class="btn btn-xs btn-default">Submit</button>
</form>
and the getSummary method in my methods object in vue is like this
methods: {
getSummary () {
axios.get('core/handle.php', {
params: {
accountNumber: this.userAcccount
}
})
.then(function (response) {
this.userData = response.data;
console.log(this.userData);
})
.catch(function (error) {
alert(error);
});
}
}
my data object contains
data: {
userAcccount: '',
userData: []
},
i am trying to update the userData with the response from axios and then use it to populate a table for testing purposes i just tried this
<span v-if="userData.length > 0">
some data
</span>
<span v-else>
data not found
</span>
console.log shows me the userData has be updated but this bit of code above doesn't change.
Using ES6 arrow functions you can access the response in the callback by rewriting slightly, like so:
.then(response => {
this.userData = response.data;
console.log(this.userData);
})
This is because you are currently reaching the axios request context with this
, which obviously is null as userData
isn't in your scope. By using the arrow function syntax you get access to the parent component where userData
resides.
You have no access to the VM via this
inside your then
function. You have three ways to fix this:
Explicitly bind the outer this
as execution context to the function (ES5 functions have their own this):
.then(function (response) {
this.userData = response.data;
console.log(this.userData);
}.bind(this))
Store the this
context in a local variable e.g. self
or that
:
getSummary () {
const self = this;
axios.get('core/handle.php', {
params: {
accountNumber: this_.userAcccount
}
})
.then(function (response) {
self.userData = response.data;
console.log(self.userData);
})
.catch(function (error) {
alert(error);
});
}
Use ES6 arrow functions which don't have their own this
:
.then(response => {
this.userData = response.data;
console.log(this.userData);
})
The concept of this
in Javascript differs alot from many other programming languages as it describes the execution context of a function. It is not an easy-to-grab concept, but this helped me get into it:
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
For reference, MDN is always a good place to go:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
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