What are some ways to implement JavaScript library functionalities within a Nuxt.js environment?

This code snippet was successfully working in an html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Kakao JavaScript SDK</title>
    <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
    <script>
        // Initialize the SDK with your app's JavaScript key
        Kakao.init('JAVASCRIPT_KEY');

        // Check if the SDK is initialized
        console.log(Kakao.isInitialized());
    </script>
</head>
<body></body>
</html>

However, when I tried to implement a similar setup in Nuxt.js, I encountered an issue:

Instead of working as expected, I received a 'ReferenceError - Kakao is not defined' in the following code snippet:

located in nuxt.config.js

// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
    title: 'P-Cloud OCR',
    meta: [
        { 'http-equiv': 'X-UA-Compatible', content: 'IE=Edge' },
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { hid: 'description', name: 'description', content: '' },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
    script: [
        { src: 'https://developers.kakao.com/sdk/js/kakao.js'},
    ]
},

This issue persisted even when I tried to include the Kakao SDK in pages/login.vue:

<script>
    export default {
    ...
}
Kakao.init('JAVASCRIPT_KEY');
console.log('Kakao.isInitialized() >>', Kakao.isInitialized());
</script>

Why is this implementation not functioning properly?

Answer №1

There are primarily two methods you can utilize:

1. Embedding the library directly into 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. Integrating the library through a plugin

Check out Josh Deltener's insightful article on how to achieve this:

Answer №2

If you want to customize the default .nuxt/views/app.template.html in nuxt, you can do so by creating an app.html file at the root of your project. Inside this file, include the following code:

app.html

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

After adding this code, you can proceed with the traditional method mentioned in your question:

<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
  <head {{ HEAD_ATTRS }}>
    {{ HEAD }}
    <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
    <script>
        // Initialize the SDK with your app's JavaScript key
        Kakao.init('JAVASCRIPT_KEY');

        // Check if the SDK is initialized
        console.log(Kakao.isInitialized());
    </script>
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>

Keep in mind that with this approach, the script will be loaded on all pages of your application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring a React JS option for filtering repeated elements, as an alternative to Angular

While using Angular JS, I came across the 'filter' option within ng-repeat which is useful for live search. Here's an example: <div ng-repeat="std in stdData | filter:search"> <!-- Std Items go here. --> </div> &l ...

Is the controller of a nested view in Angular UI router automatically considered a child of the parent view's controller?

My UI-Router setup includes a main view for products and two nested states below it. I want each nested view to have its own controller while also inheriting some basic information from the parent controller (productsCtrl). However, when attempting to acce ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements: const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Struggling to save the resolved data from a promise in Node.js to a variable

I am currently utilizing nodejs to develop REST APIs and I am facing an issue with storing resolved data from multiple promises into a single variable. Here is a snippet of the code I am working with: var resultset={}; function getAllTeams() { retu ...

Using VueJS to navigate to a specific route and pass parameters along with the

I'm a complete beginner when it comes to VueJS. Can someone please help me figure out how to access the deviceId in the Device component within vuejs? I've noticed that the deviceId in the h1 tag is not displaying on the Device component page. ...

What is the best method for establishing a many-to-many relationship between models in sequelize node.js?

I am looking to establish a many-to-many association in my Node.js application using Sequelize, as I am relatively new to the Sequelize ORM. Currently, I have a model called `user.js` and I wish to create a new model called `project` and establish a many- ...

Prevent unnecessary image resizing during parallax scrolling animation

Check out my demonstration where the image scaling results in the margin-top of the parallax wrapper being unable to dynamically adjust. Demonstration: http://jsfiddle.net/KsdeX/12/ .wrapper-parallax { margin-top: 150px; margin-bottom: 60px; } W ...

Strategies for sending data to child components in Vue

Within my parent component, I am making an API call and receiving a response. My goal is to pass this response as a prop to a child component in Vue. Below is the snippet of the parent component and the API call: <button class="btn button col-2&quo ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...

Using Javascript to populate textboxes with the value of checkboxes

Within my web application, there is a series of checkboxes that, when selected, populate a textbox located above them. If more than one checkbox is checked, their values are displayed in the textbox separated by commas. These checkboxes are structured as ...

Share an image using a subdomain in Express.js

Suppose I have the following code for testing on a local environment. sendImage: async function(req, res) { console.log(req.hostname); var filepath = path.join(__dirname, '../../img/uploads/' + req.params.year + '/' + req.para ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

What is the best way to interweave my objects within this tree using recursion?

I am working on creating a new function called customAdd() that will build a nested tree structure like the one shown below: let obj = [] let obj1 = { key: "detail1Tests", id: "94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e" } ...

Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html: <body ng-app="ysi-app" ng-controller="MainControlle ...

Incorporate a JavaScript variable within the src attribute of a script tag

Embedding Google's script allows for displaying a trends Map on our website. <script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&a ...

The error message from NPM indicates that a script named "dev" is missing, although the package.json file does contain the "dev

After running npm run dev, I encountered the error message: missing script: dev In my package.json file, the scripts section includes "dev": "nuxt" https://i.sstatic.net/yo5Ll.png https://i.sstatic.net/TJV2s.png ...