首页 > 解决方案 > 如何加载外部本地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';
    }
}

标签: vue.js

解决方案


放置在公共文件夹中;放置在 public 文件夹中的任何静态资产都将被简单地复制而不通过 webpack。您需要使用绝对路径来引用它们。

因此,您可以将外部 JS 放在公共文件夹中,并使用其路径来执行您的 JS 文件。有关更多参考,请遵循https://cli.vuejs.org/guide/html-and-static-assets.html#html

由于它不会通过 webpack,因此不推荐这样做。我建议您将此 JS 调用放在任何 Vue 生命周期挂钩中,因为将其放在公共文件夹中并不是一个好习惯。


推荐阅读