Vue Import Baidu map error: BMap is not defined, eslint BMap reports an error

When the mounted map is initialized, BMap is not defined due to asynchronous issues, that is, the map has been initialized before Baidu’s api is fully introduced or loaded.

Solution:

1. Create a 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. Reference in the .vue file 

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

3. Initialize in the mounted function

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

Undefined BMap in map.js will report an error

 

 Solution:

Make a global declaration in eslintrc.js

  globals: {
    BMap: true 
  }

 

 That’s it~~

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *