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;
都没有成功.
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.
我的控制台显示:
before: undefined
after: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
但是Vue Devtools仅显示:
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"
这是我的完整代码.
推荐答案
在data
和created
之类的选项函数中,vue为我们将this
绑定到视图模型实例,因此我们可以使用this.contas
,但在then
内部的函数中,未绑定this
.
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.
因此,您需要像这样保留视图模型(created
表示组件的数据结构已组装,在这里足够了,mounted
将使操作延迟更多):
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;
});
}
或者,如果您仅旨在支持现代浏览器(或使用像babel这样的翻译器),则可以在ES6标准中使用箭头功能,例如:
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
是根据词法上下文进行绑定的,这意味着以上代码段中的this
与我们想要的created
中的this
相同.
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.
这篇关于Axios无法设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!