1. 程式人生 > >vue 裏面異步加載高德地圖

vue 裏面異步加載高德地圖

you pro con async cal export 失敗 all 異步

前言

關於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.就解決了

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

如圖:

技術分享圖片

vue 裏面異步加載高德地圖