1

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);
        }

    });
    }
}
})

2 Answers 2

2

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);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

There are some ES2015/ES2016 approaches to consider as well, but I'm not familiar with them. See #4 onwards at sitepoint.com/bind-javascripts-this-keyword-react
You're using arrow functions, this should be exactly what you're expecting without the .bind(this).
0

instead of using 'ready' use the new functions of vue 2.0 https://v2.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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.