[英]Is there any other way to add an external js script in vue js component?
我在 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)
},
有沒有其他方法可以在計算內部的 vue js 組件中添加外部 js 腳本或任何其他方式?
首先通過 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.