問題描述:
將百度地圖封裝成一個獨立的組件BMapComponent,具體見
Vue系列:如何將百度地圖包裝成Vue的組件
(http://www.cnblogs.com/strinkbug/p/5769075.html),然后將BMapComponent作為vux的popup組件的子組件,代碼如下:
<popup :show.sync="showPositionContainer" style="position:absolute">
<b-map-component v-ref:mapviewer :map-height="mapH"></b-map-component>
</popup>
selectPosition() {
this.showPositionContainer = true
var that = this
that.$refs.mapviewer.showMap(that.mapInfo)
}
},
- //BMapComponent的showMap方法定義如下:
showMap(mapInfo) {
console.log('enter initMap')
this.mapInfo = this.cloneMapInfo(mapInfo)
this.map = new BMap.Map("allmap")
var point = new BMap.Point(this.mapInfo.longitude, this.mapInfo.latitude)
var marker = new BMap.Marker(point)
this.map.addOverlay(marker)
this.map.centerAndZoom(point, 15)
this.needCenter = false
var infoWindow = new BMap.InfoWindow(this.mapInfo.address, this.opts) // 創建信息窗口對象
this.map.enableScrollWheelZoom(true)
this.map.openInfoWindow(infoWindow, point) //開啟信息窗口
},
發現地圖總是顯示不全。
原因分析:
popup通過show屬性來控制顯示和隱藏,然后在內部通過watch該show屬性的變化,再響應事件來執行相關的顯示和隱藏的動作,由於vue是在獨立的線程中去輪訓那些被watch的變量的變化,這個輪訓是有一定的間隔的,所以屬性變化和動作執行之間是異步的。但是我們在代碼中,showPositionContainer改為true之后馬上就執行showMap,此時popup還沒顯示出來。
解決方法:
把selectPosition改為如下方式即可.
selectPosition() {
this.showPositionContainer = true
var that = this
//此處加了個延時處理,因為popup的show屬性響應沒有那么及時
window.setTimeout(function() { that.$refs.mapviewer.showMap(that.mapInfo)}, 150)
}
