javascript 在Vue.js中,如何从Google Maps click事件中调用函数?

fhity93d  于 2022-12-10  发布在  Java
关注(0)|答案(2)|浏览(167)

我在SPA模式下的Nuxt.js应用程序中使用Google Maps API,我希望从gmap click事件调用Vue.js方法中的函数
我尝试了通常的this.createInfoWindow(),但this不是VueComponent,而是Window
在我的组件中,我初始化了google maps,并在挂载的vue中添加了click事件:

async mounted() {
  // Map initalization
  const google = await gmapsInit()
  this.map = new google.maps.Map(
    document.getElementById('g-map'),
    this.mapOptions
  )
  // Add click event
  google.maps.event.addListener(this.map, 'click', e => {
    // function call not working
    this.createInfoWindow(e.latLng)
  })
}

在vue方法中,我有一个函数:

methods: {
  async createInfoWindow(latLng) {
    const google = await gmapsInit()
    const infoWindow = new google.maps.InfoWindow({
      content: 'InfoWindow',
      position: latLng
    })
    infoWindow.open(this.map)
  }
}

除了函数调用之外,所有东西似乎都在工作:this.createInfoWindow(e.latLng)
如何从click事件调用函数createInfoWindow

insrf1ej

insrf1ej1#

正如你所说的,this并不引用点击处理程序中的Vue示例。

// Add click event
  const that = this
  google.maps.event.addListener(this.map, 'click', e => {
    // function call not working
    that.createInfoWindow(e.latLng)
  })
zte4gxcn

zte4gxcn2#

“this”在listener函数中没有被访问,因此“this.createInfoWindow”的存在是未知的。闭包帮助您捕获和存储“this”,以便在子函数(本问题中的listener函数)的作用域中使用,因此Steve的解决方案有效

相关问题