动态加载js链接

function loadAMapApi (options:any) {
if (typeof document === 'undefined') {
// 只在浏览器环境加载
return
}
if (typeof (window).AMap === 'undefined') {
if (typeof options !== 'object') {
console.error('You should specify parameters for the AMap')
return
}
options['callback'] = 'vAMapInitByFlightadsb'
let baseUrl = 'https://***.***.com/'
let _scriptTab = document.createElement('script')
let url = baseUrl + 'maps?' + Object.keys(options).map(key => {
return encodeURIComponent(key) + '=' + encodeURIComponent(options[key])
}).join('&')
_scriptTab.setAttribute('src', url)
_scriptTab.setAttribute('async', '')
_scriptTab.setAttribute('defer', '')
_scriptTab.setAttribute('charset', 'utf-8')
document.head.appendChild(_scriptTab)
} else {
console.error('Has loaded the AMap!')
}
}

异步加载组件

main.ts

import vAMapPlugin from '@/plugins/amap'
// 异步加载高德地图
Vue.use(vAMapPlugin, {
v: '1.4.10',
key: 'YOU_TOKEN'
})

plugins/amap.ts

function getLoadMapPromise (options:any):Promise {
if (typeof window === 'undefined') {
return new Promise(() => {}).then(() => {
console.log('there is not window object')
})
} else {
const onGMapLoaded = () => {
console.log('%cHello! The AMap API has been downloaded!', 'color: #37ba1d;font-weight: 700;')
}
// resolve赋值给 高德地图下载完成执行回调
return new Promise((resolve, reject) => {
(window).vAMapInitByFlightadsb = resolve
loadApiOfAMap(options)
}).then(onGMapLoaded)
}
}
function installVAMapPlugin (Vue:any, options?: any):void {
let loadPromise = getLoadMapPromise(options)
// 混入到Vue对象里,方便全局调用 全局函数
Vue.mixin({
created () {
this.$aMapLoadedPromise = loadPromise
}
})
//公共组件
Vue.component('a-map', Map)
Vue.component('a-tile-layer', TileLayer)
}
// 注册一个vue插件
const VAMapPlugin = {
install: installVAMapPlugin
}
export default VAMapPlugin
console.log('%cHello! The AMap API has been downloaded!', 'color: #37ba1d;font-weight: 700;')
posted on 2025-09-23 11:55  ycfenxi  阅读(7)  评论(0)    收藏  举报