【问题标题】:Load script inside the <template> tag using nuxt.js and vue.js使用 nuxt.js 和 vue.js 在 <template> 标记内加载脚本
【发布时间】:2018-05-07 17:29:21
【问题描述】:

我正在使用 nuxt.js(基于 vue.js)构建自定义网站,我需要使用合作伙伴提供的在我的网站上加载广告,并且需要将其放置在特定位置在我的 html 代码上。所以我将它添加到我的组件模板中,但它没有呈现。 这是我正在尝试工作的代码示例

<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>

来自 src="sampleSource" 的脚本不会加载也不会执行,感谢您的帮助。非常感谢。

【问题讨论】:

    标签: vue.js vuejs2 vue-component nuxt.js


    【解决方案1】:

    在页面上,使用带有body: true 的元数据在body 中添加脚本

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

    【讨论】:

      【解决方案2】:

      您需要创建一个 (sample-source.vue) 组件并将其带到 /components 目录。 之后你需要为你的组件创建一个插件:/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'
      ]
      

      完成这些步骤后,您可以在任何地方使用您的组件。

      或者最简单的方法:

      <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>
      

      【讨论】:

        猜你喜欢
        • 2018-06-10
        • 2021-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多