Data scope in Vue.js

点点圈 提交于 2021-02-16 09:34:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!