Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vue.js - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...