hyeokluv
hyeokluv

Reputation: 397

How to use global javascript in nuxt? ( fb sdk use in mounted () )

I created the project as nuxt / koa. And, This is my code.

login.vue

...
<script>
mounted () {
    let vm = this
    window.fbAsyncInit = () => {
      FB.init({
        appId: 'my-app-id',
        cookie: true,
        xfbml: true,
        version: 'v2.8'
      })
      FB.getLoginStatus(function (response) {
        vm.statusChangeCallback(response)
      })
    }

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }
...
</script>

We are using the fb sdk initialization code in mounted () in .vue. But, I want to use global file. Is there any way?

Please answer. Thanks.

Upvotes: 3

Views: 2340

Answers (2)

dgibbs
dgibbs

Reputation: 411

to expand on the answer above, create the /plugins/fb-sdk.js file and inside you should basically have:

let vm = this
window.fbAsyncInit = () => {
  FB.init({
    appId: process.env.FB_APP_ID,
    cookie: true,
    xfbml: true,
    version: 'v2.8'
  })
  FB.getLoginStatus(function (response) {
    vm.statusChangeCallback(response)
  })
}

(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

then make sure your nuxt.config.js file is setup like above, and that's it.

Upvotes: 2

Asamoon Bao
Asamoon Bao

Reputation: 31

add fb sdk initialization code in ~/plugins and setting nuxt.config.js

like this:

module.exports = {
  ...
  plugins: [
    { src: '~plugins/fb-sdk.js', ssr: false }
  ],
  build: { ... }
}

Upvotes: 3

Related Questions