簡體   English   中英

在 VueJS 中導入外部 JavaScript 文件

[英]Importing external JavaScript file in VueJS

我正在使用 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>

您不能使用import fetch the modules from the URL ,但是您可以使用一個技巧來使用scripts from the URL

類似於附加 CDNJS 的腳本。 解決方案是您需要創建元素,然后在文檔的腳本中創建 append 該元素。

最好的解決方案是,使用已安裝的生命周期,然后創建並 append 它。

導入 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)
    },

通過這種方式注冊腳本將為您提供全局 object window中的函數訪問權限。

例如,現在我可以像這樣訪問 FontAwesome 的一些很酷的屬性:

window.FontAwesome.config

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM