vue父页面与子页面共同引用高德地图问题
程序员文章站
2022-05-25 19:50:51
...
父页面代码:
<template>
<div class="website">
<map-local :container="container" ref="compMap"></map-local>
<brief></brief>
</div>
</template>
//地图组件
import MapLocal from '../components/mapLocal.vue';
//子页面
import brief from './brief.vue'
components:{
MapLocal
},
mounted() {
this.$refs.compMap.init(117.001,131.001)
}
子页面代码:
<template>
<div class="webTwp">
<map-local :container="container" ref="compMap"></map-local>
</div>
</template>
//地图组件
import MapLocal from '../components/mapLocal.vue';
components:{
MapLocal
},
mounted() {
this.$refs.compMap.init(117.001,131.001)
}
地图组件页面代码:
<template>
<div>
<div id="container1" style="width: 100%;"></div>
</div>
</template>
<script>
import AMap from 'AMap';
import AMapUI from 'AMapUI';
export default {
props: ['posx'],
data() {
return {
map: null,
};
},
mounted() {
//console.log(this.posx)
},
methods: {
init(x,y) {
if((x != null && x != "" && x != undefined)||(y != null && y != "" && y != undefined) ){
let This = this;
This.map = new AMap.Map('container1', {
zoom: 14,
center: new AMap.LngLat(x, y)
});
this.punctuation(x, y);
}
},
//标点展示
punctuation(x, y) {
var marker = new AMap.Marker({
map: this.map,
position: [x, y]
});
}
}
};
</script>
<style scoped lang="scss">
#container1 {
height: 300px;
width: 403px;
}
#r-result {
width: 100%;
}
#suggestId {
width: 403px;
height: 45px;
border: 1px solid #e3e3e3;
padding-left: 15px;
}
#suggestId::-webkit-input-placeholder {
color: #c0c9cf;
}
#suggestId::-moz-placeholder {
/* Mozilla Firefox 19+ */
color: #c0c9cf;
}
#suggestId:-moz-placeholder {
/* Mozilla Firefox 4 to 18 */
color: #c0c9cf;
}
#suggestId:-ms-input-placeholder {
/* Internet Explorer 10-11 */
color: #c0c9cf;
}
</style>
以上代码出现问题:只显示父组件的地图。
问题原因:
地图组件中通过id挂载地图实例;引用的地图组件是共同的所以也只能显示一个地图;
<div id="container1" style="width: 100%;"></div>
This.map = new AMap.Map('container1', {
zoom: 14,
center: new AMap.LngLat(x, y)
});
解决:重新建一个地图组件,在子组件中引入新建的地图组件(主要需要把新建的地图组件id改了,不要和原来的一样)
推荐阅读