vue組件內(nèi)部引入外部js文件的方法
之所以要做這個(gè)是因?yàn)?,在一個(gè)組件內(nèi)部需要引入一個(gè)js文件來(lái)定位。如果放在index.html,這樣每個(gè)組件都會(huì)有這個(gè)js。所以需要在組件內(nèi)單獨(dú)引入。
第一種操作 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> 在頁(yè)面中調(diào)用
第三種封裝一個(gè)組件:
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>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue多頁(yè)面項(xiàng)目實(shí)現(xiàn)版本快照功能示例詳解
這篇文章主要為大家介紹了vue多頁(yè)面項(xiàng)目實(shí)現(xiàn)版本快照功能示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
VUE使用day.js顯示時(shí)分秒并實(shí)時(shí)更新時(shí)間效果實(shí)例
vue.js是目前比較流行的前端框架之一,它提供了非常多的基礎(chǔ)組件和工具庫(kù),以方便開(kāi)發(fā)者快速搭建具有可重用性的web應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于VUE使用day.js顯示時(shí)分秒并實(shí)時(shí)更新時(shí)間效果的相關(guān)資料,需要的朋友可以參考下2024-04-04
Vue axios 跨域請(qǐng)求無(wú)法帶上cookie的解決
這篇文章主要介紹了Vue axios 跨域請(qǐng)求無(wú)法帶上cookie的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
vue3中使用Apache?ECharts的詳細(xì)方法
最近在做一些數(shù)據(jù)透析的項(xiàng)目需要用到報(bào)表圖,那么報(bào)表圖好用的有老牌的ECharts,比較新意的AntV,思前馬后的想了一下還是用了Echarts,這篇文章主要介紹了vue3中使用Apache?ECharts,需要的朋友可以參考下2022-11-11

