Axios can't set data

Here's my data:

data: function(){
    return {
        contas: [{id: 3,
            nome: "Conta de telefone",
            pago: false,
            valor: 55.99,
            vencimento: "22/08/2016"}] //debug test value
    };
},

And here's my get request:

beforeMount() {
    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);
        });
},

The problem is I can't access this.contas from within axios.get(). I've tried Vue.set(this, 'contas', response.data); and window.listaPagarComponent.contas = response.data; without success.

My console shows:

before: undefined
after: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

But Vue Devtools shows only:

contas: Array[1]
  0: Object
    id: 3
    nome: "Conta de telefone"
    pago: false
    valor: 55.99
    vencimento: "22/08/2016"

Here's my full code.


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));
}