【问题标题】:In Vue.js, how to call a function from Google Maps click event?在 Vue.js 中,如何从谷歌地图点击事件中调用函数?
【发布时间】:2019-09-07 04:15:57
【问题描述】:

我在 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

【问题讨论】:

    标签: javascript google-maps vue.js nuxt.js


    【解决方案1】:

    正如您所说,this 没有在点击处理程序中引用您的 Vue 实例。使用闭包。

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

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 2015-06-06
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多