【问题标题】:Flickr app with jsonp in Vue 'Cannot set property 'data' of undefined'Vue 中带有 jsonp 的 Flickr 应用程序'无法设置未定义的属性'数据''
【发布时间】:2019-04-29 17:37:00
【问题描述】:

我刚开始使用公共 Flickr 流制作一个简单的单页照片蒸汽应用程序,但是到目前为止我所做的事情我得到了错误

'无法设置属性'data' of undefined'。

我的代码:

 <b-container>
    <b-row>
      <b-col>
      <p md="4" v-for="photo in Photos">{{photo.id}}</p>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
    import jsonp from "jsonp";

export default {
    name: 'PhotoFeed',
    data: function() {
        return {
            Photos: [],
            apiURL: "https://api.flickr.com/services/feeds/photos_public.gne?format=json"
        }
    },
    mounted(){
        this.getFlickrFeed();
    },
    methods: {
        getFlickrFeed(){
            let jsonp = require('jsonp');

            jsonp(this.apiURL, {name:'jsonFlickrFeed'}, function(err,data) {
                this.data = data;
                var self = this;
                if (err){
                    console.log(err.message);
                }
                else {
                    this.Photos = self.data;
                }
            });
        }
    }
}
</script>

【问题讨论】:

    标签: javascript vue.js vuejs2 jsonp


    【解决方案1】:

    您希望 var self = this 位于匿名函数定义之外,因此 this 关键字不会被新函数遮蔽;

    getFlickrFeed () {
        let jsonp = require('jsonp');
        var self = this;     // now self refers to the vue component and can
        // access the Photos property in data
    
        jsonp(this.apiURL, { name:'jsonFlickrFeed' }, function (err,data) {
    
            if (err){
                console.log(err.message);
            }
            else {
                // also use self.Photos to refer to the Vue component
                self.Photos = data;
            }
        });
    }
    

    最简单的是用箭头函数代替匿名函数:

    jsonp(this.apiURL, { name:'jsonFlickrFeed' }, (err, data) => {
        if (err) {
            console.log(err.message);
        }
        else {
            this.Photos = data;
        }
    })
    

    【讨论】:

      【解决方案2】:

      您可以使用箭头函数()=&gt; 并在回调上下文中使用this,如下所示:

                 jsonp(this.apiURL, {name:'jsonFlickrFeed'}, (err,data)=> {
                  this.data = data;
                  if (err){
                      console.log(err.message);
                  }
                  else {
                      this.Photos = this.data;
                  }
              });
      

      【讨论】:

        猜你喜欢
        • 2019-02-20
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 2017-09-22
        • 2019-04-10
        • 2020-01-14
        • 2021-11-27
        相关资源
        最近更新 更多