Axios无法设置数据

Gui*_*tto 37 vue.js axios

这是我的数据:

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

这是我的获取请求:

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);
        });
},
Run Code Online (Sandbox Code Playgroud)

问题是我无法this.contas从内部访问axios.get().我试着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]
Run Code Online (Sandbox Code Playgroud)

但Vue Devtools只显示:

contas: Array[1]
  0: Object
    id: 3
    nome: "Conta de telefone"
    pago: false
    valor: 55.99
    vencimento: "22/08/2016"
Run Code Online (Sandbox Code Playgroud)

这是我的完整代码.

Pan*_*潘俊杰 108

在像data和的选项函数中created,vue绑定this到我们的视图模型实例,所以我们可以使用this.contas,但在函数里面then,this没有绑定.

所以你需要保留视图模型(created意味着组件的数据结构已经组装好,这就足够了,mounted会延迟操作):

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

或者,如果您的目标是支持现代浏览器(或使用像babel这样的转换器),您可以使用ES6标准中的箭头功能,例如:

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

this内部箭头函数根据词汇上下文绑定,这意味着this上面的代码片段与in中的内容相同created,这就是我们想要的.


Fre*_*usa 19

为了能够在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));
}
Run Code Online (Sandbox Code Playgroud)