[英]In Vue.js, how to call a function from Google Maps click event?
I'm using Google Maps API in a Nuxt.js app in SPA mode and I want, from the gmap click event, to call a function in the Vue.js methods我在 SPA 模式下的 Nuxt.js 应用程序中使用 Google Maps API,我想从 gmap 单击事件调用 Vue.js 方法中的函数
I tried the usual this.createInfoWindow()
, but this
is not the VueComponent
, it's the Window
.我尝试了通常的
this.createInfoWindow()
, this
不是VueComponent
,而是Window
。
In my component I initialize the google maps and add the click event in the vue mounted:在我的组件中,我初始化了谷歌地图并在安装的 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)
})
}
And in the vue methods, I have the function:在 vue 方法中,我有以下功能:
methods: {
async createInfoWindow(latLng) {
const google = await gmapsInit()
const infoWindow = new google.maps.InfoWindow({
content: 'InfoWindow',
position: latLng
})
infoWindow.open(this.map)
}
}
Everything seems to be working, except the function call: this.createInfoWindow(e.latLng)
一切似乎都在工作,除了函数调用:
this.createInfoWindow(e.latLng)
How can I call the function createInfoWindow
from the click event?如何从点击事件中调用函数
createInfoWindow
?
As you stated, this
does not refer to your Vue instance inside the click handler.如您所述,
this
不是指单击处理程序中的 Vue 实例。 Use a closure.使用闭包。
// Add click event
const that = this
google.maps.event.addListener(this.map, 'click', e => {
// function call not working
that.createInfoWindow(e.latLng)
})
"this" is not accessed within the listener function, hence the existence of "this.createInfoWindow" is not known. “this”在侦听器函数中未被访问,因此“this.createInfoWindow”的存在是未知的。 A closure helps you capture and store "this" for use in the scope of the child function (the listener function in this problem), hence Steve's solution works
闭包可以帮助您捕获并存储“this”,以便在子函数(此问题中的侦听器函数)的范围内使用,因此史蒂夫的解决方案有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.