将vue.js应用程序中的本地脚本注入到不同的组件中



我搜索了一个答案,但找不到问题的答案。

我正在使用vue-cli进行一个vue项目,我需要将不同的脚本注入不同的页面(我使用vue-router(,更多细节请参阅:

这是我的:

o public
|
|-index.html
|
|-js
| |-script_for_all_pages.js
| |-script_for_index1.js
| |-script_for_index2.js ...
o src (my vue project)

这是我想要的:

  1. 我想在localhost的html中有一个<script src="js/script_for_all_pages.js"></script>/*
  2. 我想在localhost/index1的html中有一个<script src="js/script_for_index1.js"></script>
  3. 我想在localhost/index2的html中有一个<script src="js/script_for_index2.js"></script>

我完成了第一步,将<script>标记添加到公共文件夹中的index.html中,但我不知道如何完成最后两步。那些路由(localhost/indexx(是组件,所以我想我应该将我的脚本注入到组件index1.vue中,但当我尝试使用import "../js/index.js";导入它时,我遇到了很多错误。不管我怎么做,我都不知道该怎么做。

不起作用的程序包列表:

vue注入js

vue插件加载脚本

谢谢你的帮助!

这就是我在Vue/React中的操作方式,只需在助手中有这个函数,并在创建时从任何组件调用它:

public injectScript(url, loadAsync=true): HTMLScriptElement {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = loadAsync;
script.src = url;
document.head.appendChild(script);
return script;
}

如果您使用JS,请忽略这些类型。您还可以使用返回的脚本对象来跟踪事件:

const script = injectScript("...");
script.onLoad = () => {/*do something*/}

此外,请确保仅限于外部小部件如果这是你的代码,肯定有更好的方法

最新更新