【问题标题】:Importing external JavaScript file in VueJS在 VueJS 中导入外部 JavaScript 文件
【发布时间】:2021-03-25 07:53:09
【问题描述】:

我正在使用 Vue CLI,我想导入托管在另一台服务器上的 JavaScript 文件。我尝试的所有方法都出现了如下所示的相同错误。

我该如何解决这个问题?如何导入外部 JS 文件?

我的 Vue 文件如下所示。

<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
  <div id="app">
    <p>Test</p>

    <button @click="doSomething">Say hello.</button>
  </div>
</template>

<script>
import TestFile from "https://.../src/TestFile.js";

export default {
  data() {
    return {
      message: "<h1>anything</h1>"
    }
  },
  async mounted() {
    await TestFile.build();
  },
  methods: {
    doSomething() {
      alert(message);
    },
  },
};
</script>

<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
</style>

【问题讨论】:

    标签: javascript vue.js vue-cli


    【解决方案1】:

    您不能使用importfetch the modules from the URL,但是您可以使用scripts from the URL 的技巧。

    类似于附加CDNJS的脚本。解决方案是您需要创建元素,然后将该元素附加到文档的脚本中。

    最好的解决方案是,使用挂载的生命周期,然后创建并附加它。

    导入 FontAwesome CDN 脚本的示例:

    mounted() {
          let fontAwesome = document.createElement('script')
          fontAwesome.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js')
          document.head.appendChild(fontAwesome)
        },
    

    通过这种方式注册脚本将为您提供全局对象window中的函数访问权限。

    例如,现在我可以像这样访问 FontAwesome 的一些很酷的属性:

    window.FontAwesome.config
    

    【讨论】:

    • 谢谢!像这样导入不会给我任何错误。但是如何在我的 Vue 组件中调用这个 JS 文件中的函数呢?
    • @inbarazulay 您可以从窗口全局对象调用。
    • @InbarAzulay,我更新了答案;我希望这会对你有所帮助。
    猜你喜欢
    • 2017-02-15
    • 1970-01-01
    • 2018-08-17
    • 2022-09-22
    • 2017-02-27
    • 2018-07-11
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多