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

相关文章
相关标签/搜索