vue.js - 如何加载外部本地JS文件
问题描述
我有一个调用外部 API 的外部 JS 文件,但是当它存储在本地时,我无法在 Vue 中调用该文件。你怎么做到这一点?
以下工作完美无缺并连接到 API。
const cnp = document.createElement('script');
cnp.setAttribute('src', https://example.com/cnp.js);
document.head.appendChild(cnp);
这个或任何其他变体都不起作用。
const cnp = document.createElement('script');
cnp.setAttribute('src', '@/js/cnp.js');
document.head.appendChild(cnp);
cnp.js 包含
console.log('Hello');
var wpwlOptions = {
style: "plain",
onReady: function() {
console.log('wpwlReady.');
var p = document.querySelector('form.wpwl-form-card');
p.style.background = 'none';
}
}
解决方案
放置在公共文件夹中;放置在 public 文件夹中的任何静态资产都将被简单地复制而不通过 webpack。您需要使用绝对路径来引用它们。
因此,您可以将外部 JS 放在公共文件夹中,并使用其路径来执行您的 JS 文件。有关更多参考,请遵循https://cli.vuejs.org/guide/html-and-static-assets.html#html
由于它不会通过 webpack,因此不推荐这样做。我建议您将此 JS 调用放在任何 Vue 生命周期挂钩中,因为将其放在公共文件夹中并不是一个好习惯。
推荐阅读
- javascript - 如何在一次单击时播放两个单独的动画?
- python - Windows:使用 Python (3.6.0+) 支持编译的 Vim
- signalr - 尝试建立组连接时 Azure SignalR InvokeAsync 挂起
- amazon-web-services - 通过从 S3 读取电子邮件地址发送电子邮件
- python - 在 django 多租户中显示主页
- r - Shiny:错误:尝试渲染第二个依赖图时,quartz() 设备大小无效
- python - 在 SciPy 的内置求解器 gmres 和 bicg 中,info 代表什么?
- angular - 如何将行添加到动态材料表的角度与行数组
- node.js - 使用 node express 和 mongodb 的好友请求模式系统
- android - 如何删除远程推送中的提交但保留本地代码