A. vue外部js動態載入
vue載入遠程(網路)jsvue項目中有時候會遇到載入遠程(網路)js的情況,常用的方法有以下兩種:
以載入在線的cesium為例
在組件中可以通過window.Cesium來獲取載入的js,示例如下:
在main.js里注冊組件
注意:注冊組件一定要在newVue之前
在組件中使用:
這樣使用比較靈活還能在載入完成和載入失敗時做一些操作。
vue項目中插入外部js
script1.onload要在頁面載入js之前寫
···
constcenterRotationAd=document.getElementById("centerRotationAd");
···
VUE中如何動態編譯js需求:動態獲取一段字元串類型的js腳本,動態編譯它並且可以完美在vue中運行與之交互。
實現:動態編譯js的方式有eval和newfunction
簡單例子:
eval:
newfunction:
顯然後者更利於擴展,詳細了解區別可以參考鏈接內容:
要注意使用newFunction,在vue環境中直接賦值的方式函數作用域與賦值vue結構對象不同:
如何在.vue文件中引入外部jsVue的createElement方法,簡單的封裝一個組件解決問題。
解決方法
第一版代碼(直接在操作Dom)如下:
exportdefault{
mounted(){
consts=document.createElement('script');
s.type='text/javascript'
s.src=''
document.body.appendChild(s);
},
}
使用createElement方法:
exportdefault{
components:{
'dingtalk':{
render(createElement){
returncreateElement(
'script',
{
attrs:{
type:'text/javascript',
src:'',
},
},
);
},
},
},
}
//使用在頁面中調用
終極方案
通過封裝一個組件remote-js實現:
exportdefault{
components:{
'remote-js':{
render(createElement){
returncreateElement('script',{attrs:{type:'text/javascript',src:this.src}});
},
props:{
src:{type:String,required:true},
},
},
},
}
使用方法:
remote-jssrc=""remote-js