Vue / Google Maps infoWindow 包含点击事件

4
我在Vue项目中实现了Google Maps API,本来我会使用像vue2-google-maps这样的库,但我的一个同学告诉我最好使用原始的JavaScript API,因为我们可能会有很多标记,并且他的经验表明,在存在太多标记时库确实会遇到困难。
所以现在我创建了这个方法来使用Vue在页面上呈现Google地图 - Map:
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,然后直接添加一个事件监听器,就像这样:
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');
  });
});

但是这种方法不起作用,因为谷歌API需要一段时间来渲染元素,我唯一解决的办法是在一秒钟的超时内包装事件监听器,但现在整个过程开始感到非常糟糕...

有什么建议处理这个问题吗?

1个回答

0

我建议以下3点:

  1. 检查Google API文档是否有任何可以传递的回调函数,或者是否点击内容会发出一些监听器。那将是最好的。
  2. 为了使其工作,您可以向document添加侦听器,并检查click event.target是否与您的带有id的元素匹配。类似于这样:
 document.addEventListener("click", (event) => {
  if (event.target.id && event.target.id === standplaats.slug) {
    console.log('I\'ve been clicked');
  }
});
  1. 你可以尝试将Vue组件作为内容放置,并在其中添加@click。但我不确定这是否会起作用。只是突然想到的。

1
谢谢,我选择了第二个选项,虽然我不知道它是否最优雅,但肯定可以工作! :) - Schotsl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接