【问题标题】:How to import JS script in vue loader component?如何在 vue 加载器组件中导入 JS 脚本?
【发布时间】:2016-03-14 22:59:01
【问题描述】:

我有一个 vue 组件

vue 组件(vue-loader)

<template>
  <p>This is a template</p>
</template>
<script>
  require('main.js')
  huha()
</script>

我有

ma​​in.js

 var huha = function(){
      alert("this is huha");
    }; 
alert("this is simple alert");

在这里我收到“简单警报”,但在评估 huha() 时显示参考错误。有人可以帮我理解为什么会这样吗?

编辑

我正在尝试按以下方式使用 testimonial.js,但出现参考错误。

    <template>
      <p>This is a template</p>
      <div id="testimonial-slider"></div>
    </template>
    <script>
      require('testimonial/testimonial.js')
      require('testimonial/testimonial.css')
      var testimonial = new Testimonial('#testimonial-slider');
    </script>
    <style>
      p{
         color: red;
        }
    </style>

它给出“参考错误:未定义推荐”

【问题讨论】:

  • 我可以看看你的组件代码吗?
  • 实际上我在这个应用程序中使用了 vue-loader webpack。所以在 vue-component 中,我们将 html、脚本和样式写在同一个文件中,扩展名为 '. vue-component' 所以我没有定义一个单独的组件。我的组件是'vue-component'
  • module.exports 仅适用于编译器,例如 browserify。你的构建过程是什么?
  • 我正在使用 webpack。我也在使用 vue-loader

标签: javascript webpack babeljs vue.js


【解决方案1】:

你需要像这样导出一个函数:

module.exports = {
    huha: function(){
      return alert("this is huha");
    }
}; 

然后在你的组件文件中:

<template>
  <p>This is a template</p>
</template>
<script>
  var main = require('main.js')
  main.huha()
</script>

【讨论】:

  • 我已经这样做了,但它不起作用?我需要 'testimonial.js' 库,所以当我执行 'require("testimonial")' 然后使用这个库函数和对象时,会引发引用错误。
  • @AshviniKumar 你是如何使用这个库的?每个组件都有范围。您可能引用了超出范围的库。
  • @YauheniPrakopchyk 我已经更新了问题,请查看问题的编辑版本
猜你喜欢
  • 2019-10-04
  • 2020-06-11
  • 2019-05-12
  • 2020-07-14
  • 2019-01-30
  • 2020-05-13
  • 1970-01-01
  • 2019-09-16
  • 2020-06-25
相关资源
最近更新 更多