gpt4 book ai didi

javascript - 在 Vue.js 中,如何从 Google map 点击事件中调用函数?

转载 作者:行者123 更新时间:2023-11-30 11:05:42 33 4
gpt4 key购买 nike

我在 SPA 模式下的 Nuxt.js 应用程序中使用 Google Maps API,我想从 gmap 单击事件调用 Vue.js 方法中的函数

我尝试了通常的 this.createInfoWindow(),但是 this 不是 VueComponent,而是 Window.

在我的组件中,我初始化了谷歌地图并在已安装的 vue 中添加了点击事件:

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)

如何从点击事件中调用函数 createInfoWindow

最佳答案

如您所述,this 不引用单击处理程序中的 Vue 实例。使用闭包。

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

关于javascript - 在 Vue.js 中,如何从 Google map 点击事件中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718696/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com