Load script inside the <template> tag using nuxt.js and vue.js

Viewed 3401

I am using nuxt.js (which is based on vue.js) to build a custom website, I need to load an Ad on my website using a provided by my partners, and I need to place it at a specific place on my html code. So I add it to my component template but it does not render. Here is a sample of the code I'm trying to get to work

<template>
  <div>
    <div class="columns is-centered is-mobile">
      <p>Hello World</p>
    </div>
    <div>
      <script type="text/javascript" src="sampleSource"></script>
    </div>
  </div>
</template>
<script>
  export default {
  }
</script>

the script that comes from src="sampleSource" doesn't load and doesn't execute, any help is appreciated. Thank you very much.

2 Answers

On the page, use in metadata with body: true for add script inside body

<script>
export default {
  head: {
    script: [
      { src: '/head.js' },
      // Supported since Nuxt 1.0
      { src: '/body.js', body: true },
      { src: '/defer.js', defer: '' }
    ]
  }
}
</script>

You need to create a (sample-source.vue) component and take it to the /components dir. After that you need to create a plugin for your component: /plugins/sample-source.js

sample-source.js :

import Vue from 'vue'
import SampleSource from '~/components/sample-source.vue'

Vue.use(SampleSource)

nuxt.config.js:

...
module.export
...
plugins: [
  '~/plugins/sample-source.js'
]

After these steps you can use your component everywhere.

Or the easiest way:

<template>
  <div>
    <div class="columns is-centered is-mobile">
      <p>Hello World</p>
    </div>
  </div>
</template>
<script>
  export default {
    mounted () {
----your code here from sampleSource.js----
    }
  }
</script>
Related