无法让jsonp回调在Vue组件中工作

时间:2019-07-07 18:10:06

标签: vue.js jsonp flickr

我正在尝试使用这个Flickr jsonp Vue示例(https://codepen.io/tomascherry/pen/GrgbzQ)并将其变成一个组件。但是,我无法弄清楚如何将jsonFlickrFeed()映射到this.jsonFlickrFeed()(一旦该函数放置在组件的methods: {}内部)。

代码如下:

<template>
  <!-- HTML HERE -->
</template>

<script>
let callApiTimeout = null

export default {
  name: 'Flickr',
  filters: {
    splitTags: function(value) {
      // showing only first 5 tags
      return value.split(' ').slice(0, 5)
    }
  },
  directives: {
    /* VueJs utilites */
    img: {
      inserted: function(el, binding) {
        this.lazyload(el, binding)
      },
      update: function(el, binding) {
        this.lazyload(el, binding)
      }
    }
  },
  data() {
    return {
      images: [],
      query: ''
    }
  },
  watch: {
    query: function(value) {
      clearTimeout(callApiTimeout)
      callApiTimeout = setTimeout(
        function() {
          const reqURL =
            'https://api.flickr.com/services/feeds/photos_public.gne'
          const options = {
            params: {
              format: 'json',
              tags: this.query,
              jsoncallback: 'this.jsonFlickrFeed'
            }
          }
          this.$http.jsonp(reqURL, options)
        }.bind(this),
        250
      )
    }
  },
  methods: {
    /* JSONP callback function */
    jsonFlickrFeed(response) {
      this.$data.images = response.items
    },
    /* General utility functions */
    lazyload(el, binding) {
      const img = new Image()
      img.src = binding.value

      img.onload = function() {
        el.src = binding.value
      }
    }
  }
}
</script>

<style lang="less">
  /* STYLE HERE */
</style>

我尝试添加jsoncallback: 'this.jsonFlickrFeed'参数,但这无济于事。

1 个答案:

答案 0 :(得分:0)

为简化起见,只需传递参数nojsoncallback=1,它将直接返回JSON对象。