Vue.js 中的数据范围 [英] Data scope in Vue.js
本文介绍了Vue.js 中的数据范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 vue.js 的新手我正在使用下面的代码并遇到一些问题.我试图使用 this.myData
在方法对象中的方法 myFunction
内的 for 循环中访问数据 myData,但它无法访问/超出范围
I'm new to vue.js I'm working with the code below and run into some problem. I was trying to access data myData within a for loop within a method myFunction
in the method object using this.myData
but it is inaccessible/out of scope
export default MyComponent.extend({
data:function(){
return {
myData: []
}
},
ready:function(){
this.myFunction();
},
methods:{
myFunction:function(){
Vue.http.get('/getdata').then((response) => {
for (var i = 0; i < response.data.info.length; i++) {
this.myData.push(response.data.info[i].address);
}
});
}
}
})
推荐答案
你说得对,这是一个范围问题.您的 then()
函数具有不同的范围.您可以在函数的末尾 .bind(this)
将 this
传递给函数.
You're correct, this is a scope issue. Your then()
function has a different scope. You can .bind(this)
at the end of your function to pass this
to the function.
Vue.http.get('/getdata').then((response) => {
for (var i = 0; i < response.data.info.length; i++) {
this.myData.push(response.data.info[i].address);
}
}.bind(this));
您可能经常看到的另一种方法是别名this
:
Another approach you may often see is aliasing this
:
var self = this;
Vue.http.get('/getdata').then((response) => {
for (var i = 0; i < response.data.info.length; i++) {
self.myData.push(response.data.info[i].address);
}
});
这篇关于Vue.js 中的数据范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文