【发布时间】:2021-03-19 06:05:08
【问题描述】:
我在一个 Vue 项目中实现了 Google Maps API,我会使用像 vue2-google-maps 这样的库,但我的一所大学告诉我最好使用纯 JavaScript API,因为我们可能有很多标记,根据他的经验,当标记很多时,图书馆真的很挣扎。
所以现在我创建了这个方法来使用 Vue 在页面上呈现谷歌地图 - 地图:
methods: {
async generateMap() {
// Start and await Google script
const google = await gmapsInit();
// Create Google Map object
this.map = new google.maps.Map(this.$el, {
zoom: 7,
center: new google.maps.LatLng(52.100886023504415, 5.6446197918489)
});
// Standplaats is an object containg a name, lat, lon and slug
this.standplaatsen.forEach(standplaats => {
const position = {
lat: standplaats.location.latitude,
lng: standplaats.location.longitude
};
// Create the marker and add to map
const marker = new google.maps.Marker({
position: position,
title: standplaats.name,
map: this.map,
});
marker.addListener("click", () => {
const infoWindow = new google.maps.InfoWindow({
content:
`<div>` +
`<h4>${standplaats.name}</h4>` +
`${standplaats.location.street}<br/>` +
`${standplaats.location.zipcode} ${standplaats.location.location}<br/>` +
`<hr/>` +
`<a>${standplaats.posts} opdrachten beschikbaar</a>` +
`</div>`
});
infoWindow.open(this.map, marker);
});
});
},
}
infoWindow 包含一个超链接 (<a>${standplaats.posts} opdrachten beschikbaar</a>),我想在单击此超链接时触发一个 Vue emit 事件。由于此 HTML 是通过 Google API 呈现的,因此我不能只包含 @click 事件。
我想到的解决方案是在超链接元素中包含一个唯一的 ID,然后直接添加一个 eventListeren,所以像这样
marker.addListener("click", () => {
const infoWindow = new google.maps.InfoWindow({
content:
`<div>` +
`<h4>${standplaats.name}</h4>` +
`${standplaats.location.street}<br/>` +
`${standplaats.location.zipcode} ${standplaats.location.location}<br/>` +
`<hr/>` +
`<a id="${standplaats.slug}">${standplaats.posts} opdrachten beschikbaar</a>` +
`</div>`
});
infoWindow.open(this.map, marker);
document.getElementById(`${standplaats.slug}`).addEventListener("click", () => {
console.log('I\'ve been clicked');
});
});
但这不起作用,因为 Google API 需要一段时间来呈现元素,我可以解决这个问题的唯一方法是将 eventListerener 包装在 1 秒超时中,但整个事情开始感觉很糟糕的做法现在就...
对如何处理有什么建议吗?
【问题讨论】:
标签: javascript vue.js vuejs2