Search code examples
vue.jsjsonpflickr

Can't get jsonp callback to work inside a Vue component


I'm trying to take this Flickr jsonp Vue example (https://codepen.io/tomascherry/pen/GrgbzQ) and turn it into a component. However, I cannot figure out how to get jsonFlickrFeed() to map to this.jsonFlickrFeed() (once that function is place inside the component's methods: {}).

Code as follows:

<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>

I tried adding the jsoncallback: 'this.jsonFlickrFeed' parameter but that doesn't help.


Solution

  • To make it simpler, just pass the parameter nojsoncallback=1 and it will return the JSON object directly.