vue引入百度地圖 --BMap is not defined ,eslint BMap報錯

在mounted初始化地圖的時候,由於異步問題會致使BMap is not defined,也就是百度的api還沒徹底引入或者加載完成,就已經進行地圖初始化了javascript

解決方法:vue

1.建立一個map.jsjava

export function MP(ak) {
  return new Promise(function(resolve, reject) {
    window.init = function() {
      resolve(BMap)
    }
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `http://api.map.baidu.com/api?v=2.0&ak=${ak}&callback=init`
    script.onerror = reject
    document.head.appendChild(script)
  })
}

2.在 .vue文件中引用 api

import { MP } from '../map.js'

3.在mounted函數中進行初始化app

   this.$nextTick(() => {
      const _this = this
      MP(_this.ak).then(BMap => {
        _this.initMap()
      })
    })

map.js 中 BMap未定義 會報錯異步

 

 解決方法:函數

在eslintrc.js中進行全局聲明this

  globals: {
    BMap: true
  }

 

 這樣就完成啦~~spa

相關文章
相關標籤/搜索