动态加载js链接、异步传参加载组件、有趣打印
动态加载js链接
- 动态加载js链接
- 异步加载组件
动态加载js链接
function loadAMapApi (options:any) {if (typeof document === 'undefined') {// 只在浏览器环境加载return}if (typeof (<any>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<any> {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) => {(<any>window).vAMapInitByFlightadsb = resolveloadApiOfAMap(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;')