Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

vue.js - Include external javascript file in a nuxt.js page

I have a relatively simple question.

I am trying to implement the widget from this codepen in Nuxt.js.

Here's my code, which works fine if I use RAW HTML:

<!DOCTYPE html>
<html>
<head></head>
<body>
  <dev-widget data-username="saurabhdaware"></dev-widget>
  <script src="https://unpkg.com/[email protected]/dist/card.component.mjs" type="module"></script>
</body>

</html>

But when I try to include this dev widget in my nuxt.js project, in one of my pages, it does not work.

Here is my code:

<template>
  <div class="container">

    <div>
        <dev-widget data-username="saurabhdaware"></dev-widget>
    </div>

  </div>
</template>

<script>

export default {
  layout: "default",
};
</script>

<script src="https://unpkg.com/[email protected]/dist/card.component.mjs" type="module"></script>

I keep getting an error:

Unknown custom element: < dev-widget >

Any idea what I am doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Adding as globally

Navigate to the nuxt.config.js file. It adds the script tag to all pages in your Nuxt app.

export default {
  head: {
    script: [
      {
        src: "https://code.jquery.com/jquery-3.5.1.min.js",
      },
    ],
  }
  // other config goes here
}

If you want to add a script tag before closing the </body> instead of <head> tag, you can do it by adding a body: true.

script: [
  {
    src: "https://code.jquery.com/jquery-3.5.1.min.js",
    body: true,
  },

You can also add async, cross-origin attributes to a script tag like this.

script: [
  {
    src: "https://code.jquery.com/jquery-3.5.1.min.js",
    async: true,
    crossorigin: "anonymous"
  },
],

OUTPUT

<script data-n-head="ssr" src="https://code.jquery.com/jquery-3.5.1.min.js"
crossorigin="anonymous" async=""></script>

Adding to particular page

<script>
  export default {
    head() {
      return {
        script: [
          {
            src: 'https://code.jquery.com/jquery-3.5.1.min.js'
          }
        ],
      }
    }
  }
</script>

Note: If you want to add a local js file, place it in a root static folder and add it as follows.

  export default {
    head() {
      return {
        script: [
          {
             src: '/js/jquery.min.js'
          }
        ],
      }
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...