这是我的数据:
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);
});
},
问题是我无法从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]
但Vue Devtools只显示:
contas: Array[1]
0: Object
id: 3
nome: "Conta de telefone"
pago: false
valor: 55.99
vencimento: "22/08/2016"
这是我的full code。
答案 0 :(得分:92)
在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;
});
}
或如果您的目标是支持现代浏览器(或使用像babel这样的转发器),您可以使用ES6标准中的箭头功能,例如:
created() {
axios.get('http://127.0.0.1/api/bills')
.then((response) => {
this.contas = response.data;
});
}
箭头函数中的 this
根据词汇上下文绑定,这意味着上述代码段中的this
与created
中的{{1}}相同,这就是我们想要的。 / p>
答案 1 :(得分:12)
为了能够在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));
}
答案 2 :(得分:0)
是的,我想我需要发布另一个问题,因为问题现在不同了。但是为了能够访问this.contas
,我刚刚用beforeMount () {}
替换了mounted: function () {}
。