vue 里面異步加載高德地圖


前言

關於Vue 里面使用異步加載高德地圖

  • 項目中其實只有幾處需要用到地圖,不需要全局引入
  • 在index文件中引入js會明顯拖慢首屏加載速度,雖然可以使用異步加載script的方式解決,但是始終覺得不夠優雅。

解決方案

1.創建一個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)
    }
  })
}
2. 在任何.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.就解決了 

  一個異步加載的高德地圖插件,不需要在全局引入,也不用擔心功能不齊全,其他的東西,完全參照高德地圖官方文檔來設置即可。

如圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM