1

This is my first time to play with Vue.js but I need to use Facebook SDK for login.

Many documents emphasize that the Facebook SDK must first be loaded asynchronously.

I know there are a couple of Q&As on this topic at StackOverflow, but my case differs.

  1. Using the created method while creating a new Vue instance
    I cannot use this option because I'm using vue-router and only one component will use Facebook SDK for login.

  2. Using nuxt.js
    I don't know much about Vue.js yet. Trying nuxt.js seems like opening up a whole new can of worms.

Is there any example of loading Facebook SDK asynchronously in a Vue.js single-file component?

tony19
  • 125,647
  • 18
  • 229
  • 307
user19906
  • 323
  • 4
  • 12

1 Answers1

2

After doing the following you can call any of the SDK functions, like the login one, like this: Vue.FB.login(). Initialize the SDK before you call the Vue constructor. In lib/FacebookSdk.js:

const initFbSdk = (Vue, facebookClientId) => {
  window.fbAsyncInit = () => {
    FB.init({
      appId: facebookClientId,
      autoLogAppEvents: true,
      xfbml: true,
      version: 'v3.2',
    });
    Vue.FB = FB;
  };
};

And in main.js:

import { initFbSdk } from './lib/FacebookSdk';

// ...

initFbSdk(Vue, process.env.VUE_APP_FACEBOOK_CLIENT_ID);

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');

Use it in your components or anywhere else like

import Vue from 'vue';

// ...

Vue.FB.login(resp => {
    // ...
});