问题
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);
}
});
}
}
})
回答1:
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));
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);
}
});
回答2:
instead of using 'ready' use the new functions of vue 2.0 https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
you can use mounted () {this.myFunction ()}
when executing the function you can already see the data ()
of the component
来源:https://stackoverflow.com/questions/39707325/data-scope-in-vue-js