[Vuejs]-Custom components showing counts from Facebook API

0πŸ‘

βœ…

The issue is the way that you are returning the count:

count: function() {
  // This first return is what is actually returned and that is
  // a jQuery object
  return $.getJSON('https://api.facebook.com/method/links.getStats?urls=' + this.src + '&format=json').done(function(data) {
    console.log(data[0].click_count);

    // This return does not get returned
    // like you think it gets returned
    return data[0].click_count;
  });
}

Here is one way to resolve the issue that you are having:

var FBShare = Vue.extend({
    props: ['src'],
    data: function() { return { count: '' } },
    ready: function() {
        this.loadCount();
    },
    methods: {
        loadCount: function() {
            var _this = this;
            $.getJSON('https://api.facebook.com/method/links.getStats?urls=' + this.src + '&format=json').done(function(data) {
                console.log(data[0].click_count);
                _this.count = data[0].click_count;
            });
        }
    },
    template: '<span>{{ src }} - {{ count }}</span>'
});


Vue.component('fb-share', FBShare);

new Vue({
    el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="app">
  <fb-share src="http://google.com"></fb-share>
</div>

0πŸ‘

Never mind, I found the answer.

I add the vue-resource and revise the code from it.

Here it is.

var FBShare = Vue.extend({
  props: ['src'],
  data: function(){
    return { props: {} };
  },
  ready: function(){
this.$http.get('https://api.facebook.com/method/links.getStats?urls=' + this.src + '&format=json', function(data){
      this.props = data;
    });
  },
  template: '<span>{{ src }} - {{ props[0].share_count }}</span>'
});

Vue.component('fb-share', FBShare);

new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.16/vue-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="app">
  <fb-share src="http://google.com"></fb-share>
  <fb-share src="http://kawaiibeautyjapan.com"></fb-share>
</div>

Leave a comment