在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 }
這樣就完成啦~~