【问题标题】:Is there any other way to add an external js script in vue js component?有没有其他方法可以在 vue js 组件中添加外部 js 脚本?
【发布时间】:2021-04-12 19:01:25
【问题描述】:

我正在像这样在 vue js 组件中添加一个外部 js 脚本:

mounted() {
                let spotlighterScript = document.createElement('script')
                spotlighterScript.setAttribute('src', 'www.domain.com/assets/demo.js')
                spotlighterScript.setAttribute('Content-Type', 'text/javascript')
                document.head.appendChild(spotlighterScript)
            },

有没有其他方法可以在compute内部的vue js组件中添加外部js脚本或其他方式?

【问题讨论】:

标签: javascript reactjs vue.js vuejs2 vue-component


【解决方案1】:

方法一使用插件

首先通过 npm 或 yarn 安装 vue-plugin-load-script

npm install --save vue-plugin-load-script

在 main.js 中添加

import LoadScript from 'vue-plugin-load-script';

Vue.use(LoadScript);

Vue.loadScript(scriptUrl)
 .then(() => {
   // Script is loaded, do something
 })
 .catch(() => {
   // Failed to fetch script
 });

感谢@halilcakar 提及此方法。直到你展示它我才知道这个插件。

方法二手动实现

mounted() {
    //script already loaded exit
    if (document.getElementById('external-source-script')) return;

    //Create script tag
    let script = document.createElement('script')
    script.setAttribute('src', 'your-external-source') // <---------------
    script.setAttribute('type', 'text/javascript')
    script.setAttribute('id', 'external-source-script')
 
    //Add external script dependency 
    document.head.appendChild(script)
}


beforeDestroy() {
    //Remove the external source
    let el = document.getElementById('external-source-script')
    if (el) el.remove();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 2021-10-03
    • 2018-11-09
    • 1970-01-01
    • 2019-06-23
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多