vue組件內(nèi)部引入外部js文件的方法
更新時間:2020年01月18日 14:37:04 作者:竿牘
這篇文章主要介紹了vue組件內(nèi)部引入外部js文件的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
之所以要做這個是因為,在一個組件內(nèi)部需要引入一個js文件來定位。如果放在index.html,這樣每個組件都會有這個js。所以需要在組件內(nèi)單獨引入。
第一種操作 Dom引入js:
export default {
mounted() {
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = '你的需要的js文件地址';
document.body.appendChild(s);
},
}
第二種使用 createElement 方法:
export default {
components: {
'remote-js': {
render(createElement) {
return createElement(
'script',
{
attrs: {
type: 'text/javascript',
src: '你的需要的js文件地址',
},
},
);
},
},
},
}
// 使用 <remote-js></remote-js> 在頁面中調(diào)用
第三種封裝一個組件:
importJs.js
// 導(dǎo)入外部js
import Vue from 'vue'
Vue.component('remote-script', {
render: function (createElement) {
var self = this;
return createElement('script', {
attrs: {
type: 'text/javascript',
src: this.src
},
on: {
load: function (event) {
self.$emit('load', event);
},
error: function (event) {
self.$emit('error', event);
},
readystatechange: function (event) {
if (this.readyState == 'complete') {
self.$emit('load', event);
}
}
}
});
},
props: {
src: {
type: String,
required: true
}
}
});
// 引入
import 'common/importJs.js'
// 使用
<remote-script src="https://pv.sohu.com/cityjson?ie=utf-8"></remote-script>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue3中使用Apache?ECharts的詳細(xì)方法
最近在做一些數(shù)據(jù)透析的項目需要用到報表圖,那么報表圖好用的有老牌的ECharts,比較新意的AntV,思前馬后的想了一下還是用了Echarts,這篇文章主要介紹了vue3中使用Apache?ECharts,需要的朋友可以參考下2022-11-11

