vue引入百度地图 --BMap is not defined ,eslint BMap报错

在mounted初始化地图的时候,因为异步问题会导致BMap is not defined,也就是百度的api还没完全引入或者加载完成,就已经进行地图初始化了

解决方法:

1.创建一个map.js

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文件中引用 

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

3.在mounted函数中进行初始化

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

map.js 中 BMap未定义 会报错

 

 解决方法:

在eslintrc.js中进行全局声明

  globals: {
    BMap: true
  }

 

 这样就完成啦~~

 

posted @ 2019-11-12 14:19  _skylar  阅读(13486)  评论(2编辑  收藏  举报