關於Vue 裏面使用異步加載高德地圖javascript
AMap.js
,路徑'
utils/AMap'export default function MapLoader () { // <-- 原做者這裏使用的是module.exports return new Promise((resolve, reject) => { if (window.AMap) { resolve(window.AMap) } else { var script = document.createElement('script') script.type = 'text/javascript' script.async = true script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=yourkey' script.onerror = reject document.head.appendChild(script) } window.initAMap = () => { resolve(window.AMap) } }) }
.vue
文件中使用// test.vue <template> <div class="test"> <div id="container" class="h300 w300"></div> </div> </template> <script> import MapLoader from '@/utils/AMap'
export default { name: 'test', data () { return { map: null } }, mounted () { let that = this MapLoader().then(AMap => { console.log('地圖加載成功') that.map = new AMap.Map('container', { center: [117.000923, 36.675807], zoom: 11 }) }, e => { console.log('地圖加載失敗' ,e) }) } } </script>
3.就解決了 vue
一個異步加載的高德地圖插件,不須要在全局引入,也不用擔憂功能不齊全,其餘的東西,徹底參照高德地圖官方文檔來設置便可。java
如圖:web