[Vuejs]-How can I use javascript library function in nuxt.js?

0👍

There are basically 2 approaches you can do:

1. Load the library directly in your layout/page/component

head () {
  if (window.Kakao) {
    this.afterKakaoLoaded()
    return
  }

  return {
    script: [
      {
        hid: 'kakao',
        src: 'https://developers.kakao.com/sdk/js/kakao.js',
        callback: () => {
          this.afterKakaoLoaded()
        }
      }
    ]
  }
},

methods: {
  afterKakaoLoaded () {
    window.Kakao.init('...')
  }
}

2. Load the library within a plugin

Josh Deltener wrote a great article about how to achieve that: https://deltener.com/blog/nuxt-third-party-code-is-poison/

0👍

In nuxt you can overwrite the default .nuxt/views/app.template.html.

You need to create app.html file at the root of the project. Then put the below code inside this file:

app.html

<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
  <head {{ HEAD_ATTRS }}>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>

Then you can follow the traditional way that you mentioned in question:

<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
  <head {{ HEAD_ATTRS }}>
    {{ HEAD }}
    <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
    <script>
        // SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
        Kakao.init('JAVASCRIPT_KEY');

        // SDK 초기화 여부를 판단합니다.
        console.log(Kakao.isInitialized());
    </script>
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>

But be aware that in this method, all pages in your application load this script.

Leave a comment