【问题标题】: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();
}