如何在Vue CLI组件中使用多外部CDN JavaScript文件

时间:2019-05-19 00:57:16

标签: javascript vue.js

我尝试通过各种方法mounted()created()在Vue Component中包含外部JS文件,但最终没有任何解决方案对我有用。我不确定我想念的地方。 任何帮助将不胜感激:)

代码如下:

<template>
  <div id="sketchy"></div>
</template>

<script>

export default {
  data(){
    return {
    }
  }, mounted() {
      if (document.getElementById('sketchy')) return; // was already loaded
      var scriptTag = document.createElement("script");
      scriptTag.src = "https://bootswatch.com/_vendor/jquery/dist/jquery.min.js";
      scriptTag.id = "sketchy";
      document.getElementsByTagName('head')[0].appendChild(scriptTag);
  },
   mounted() {
      if (document.getElementById('sketchy')) return; // was already loaded
      var scriptTag = document.createElement("script");
      scriptTag.src = "https://bootswatch.com/_vendor/popper.js/dist/umd/popper.min.js";
      scriptTag.id = "sketchy";
      document.getElementsByTagName('head')[0].appendChild(scriptTag);
  },
  mounted() {
      if (document.getElementById('sketchy')) return; // was already loaded
      var scriptTag = document.createElement("script");
      scriptTag.src = "https://bootswatch.com/_vendor/bootstrap/dist/js/bootstrap.min.js";
      scriptTag.id = "sketchy";
      document.getElementsByTagName('head')[0].appendChild(scriptTag);
  },
}
</script>


<style scoped>

</style>

1 个答案:

答案 0 :(得分:0)

我尝试了以下方法。这3个脚本文件已导入 head 标记中。

mounted:function(){
//   if (document.getElementById('sketchy')) {
//       console.log("loadeddd");
//         return;
//   } // was already loaded
  var scriptTag = document.createElement("script");
//   scriptTag.src = "https://bootswatch.com/_vendor/jquery/dist/jquery.min.js";
  scriptTag.setAttribute('src','https://bootswatch.com/_vendor/jquery/dist/jquery.min.js?onload=onLoad')
//   scriptTag.id = "sketchy";
  //scriptTag.setAttribute('id','sketchy');
  scriptTag.async=true;
  scriptTag.defer=true;
  document.getElementsByTagName('head')[0].appendChild(scriptTag);
  console.log("scripttag1 createddd");

  var scriptTag1 = document.createElement("script");
  scriptTag1.setAttribute('src','https://bootswatch.com/_vendor/popper.js/dist/umd/popper.min.js?onload=onLoad');
  scriptTag1.async=true;
  scriptTag1.defer=true;
  document.getElementsByTagName('head')[0].appendChild(scriptTag1);
  console.log("scriptag2 createdd");


  var scriptTag2 = document.createElement("script");
  scriptTag2.setAttribute('src','https://bootswatch.com/_vendor/bootstrap/dist/js/bootstrap.min.js?onload=onLoad');
  scriptTag2.async=true;
  scriptTag2.defer=true;
  document.getElementsByTagName('head')[0].appendChild(scriptTag2);
  console.log("scriptag3 createdd");

}