axios 无法设置数据

Axios can't set data

这是我的数据:

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

这是我的获取请求:

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

问题是我无法从 axios.get() 访问 this.contas。我试过 Vue.set(this, 'contas', response.data);window.listaPagarComponent.contas = response.data; 都没有成功。

我的控制台显示:

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

但是 Vue Devtools 只显示:

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

这是我的 full code

在像datacreated这样的选项函数中,vue为我们绑定了this到view-model实例,所以我们可以使用this.contas,但是在thenthis 中的函数未绑定。

所以你需要保留view-model like(created表示组件的数据结构组装好了,这里就够了,mounted会延迟操作更多):

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

或者 如果你只是想支持现代浏览器(或者使用像 babel 这样的编译器),你可以使用 ES6 标准中的箭头函数,比如:

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

this里面的箭头函数是根据词法上下文绑定的,也就是说上面代码片段中的thiscreated中的是一样的,这就是我们想要的.

为了能够在 axios.get() 中访问 this.contas,您是否需要绑定 "this" 以保持变量使用范围:

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