可以简单封装个异步加载入口const KEY = ''; // 填写你自己申请的key let mapInit = false; let mapLoad = false; let callbacks = []; function qqMap(libraries) { return new Promise(resolve => { if (!mapInit) { const script = document.createElement('script'); const callbackName = 'onQQMapLoad'; libraries = libraries || 'drawing,geometry,convertor'; script.src = `//map.qq.com/api/js?v=2.exp&key=${KEY}&libraries=${libraries}&callback=${callbackName}`; window[callbackName] = () => { mapLoad = true; for (const callback of callbacks) { callback(window.qq); } callbacks = []; }; document.body.appendChild(script); mapInit = true; } else if (mapLoad) { resolve(window.qq); } else { callbacks.push(resolve); } }); } export default qqMap; 在组件中使用<template> <div ref="map" style="width: 100%; height:500px;"></div> </template> <script> import qqMap from '@/utils/qq-map.js'; export default { mounted() { qqMap().then(qq => { new qq.maps.Map(this.$refs.map, { zoom: 8, mapTypeId: qq.maps.MapTypeId.ROADMAP, }); }); }, }; </script>
可以简单封装个异步加载入口
在组件中使用