Axios can't set data Axios can't set data vue.js vue.js

Axios can't set data


In option functions like data and created, vue binds this to the view-model instance for us, so we can use this.contas, but in the function inside then, this is not bound.

So you need to preserve the view-model like (created means the component's data structure is assembled, which is enough here, mounted will delay the operation more):

created() {    var self = this;    axios.get('http://127.0.0.1/api/bills')        .then(function (response) {                self.contas = response.data;                });}

Or you can use arrow function in ES6 standard if you only aim to support modern browsers(or using a transpiler like babel), like:

created() {    axios.get('http://127.0.0.1/api/bills')        .then((response) => {                this.contas = response.data;                });}

this inside arrow functions are bound according to lexical context, which means the this in the above snippet is the same as the one in created, which is what we want.


To be able to access this.contas inside axios.get() do you need binding "this" to keep variable usage scoped:

mounted() {    axios.get('http://127.0.0.1/api/bills')     .then(function (response) {        console.log("before: " + this.contas);        this.contas = response.data;        console.log("after: " + this.contas);     }.bind(this));}