问题描述:在vue中加载百度地图, 当初始化时,第一次加载地图时,可以正常显示地图,当切换路由再次进入地图时,地图只显示上部一部分地图。
问题原因:
that.map = new BMap.Map("b_map", {
enableMapClick: false,
mapType: BMAP_NORMAL_MAP
});
地图创建只需要初始化一次,或重新加载一次,map多次初始化后,地图就会出现问题;
data() {
return {
mapHeight: 0,
map: null
}
},
mounted() {
this.init()
},
methods: {
init() {
this.baiDuMap()
this.mapHeight = window.innerHeight - 240
window.onresize = () => {
this.mapHeight = window.innerHeight - 240
}
},
baiDuMap() {
let that = this
that.map = new BMap.Map("b_map", {
enableMapClick: false,
mapType: BMAP_NORMAL_MAP
});
let point = new BMap.Point(119.160414, 36.817672);
that.map.centerAndZoom(point, 13)
that.map.setCurrentCity("潍坊") //设置当前显示城市
that.map.enableScrollWheelZoom()
that.map.enableKeyboard()
// 左下角,添加比例尺
let top_left_control =
new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT})
that.map.addControl(top_left_control)
}
}
解决方法:
<div class="app-container">
<Content class="wrap-content">
<keep-alive>
<router-view :title="sidebarSecondTitle"/>
</keep-alive>
</Content>
</div>
keep-alive是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。
使用Vue组件切换过程钩子activated(keep-alive组件激活时调用),或挂载钩子mounted:
两者的主要区别就是:activated每次切换路由后重新加载,mounted每次切换路由后不再重新加载。