首页 > 解决方案 > 在 vue 组件内的 javascript 实例化组件上添加事件处理程序。(google.maps.DirectionsRenderer)

问题描述

我们有一个 vue 应用程序,其中包含一个使用 Google 方向 API 的 google 应用程序组件。为此,我们启动地图,并创建一个 DirectionsService 实例和一个 DirectionsRenderer 实例。我们需要在路由更改时调用一个函数。

methods: {
    initMap() {
      if (this.$refs.baseMap) {
        this.$refs.baseMap.$mapPromise.then(map => {

          this.directionsService = new google.maps.DirectionsService

          this.directionsRenderer = new google.maps.DirectionsRenderer({
              draggable: true,
              map: map,
            })

          this.directionsRenderer.addListener('directions_changed', 
            function() {
              this.computeTotalDistance()  // I need this to be a called when the direction change
            }
          )
        })
      }
    },
    computeTotalDistance(){
      // do some code
    }

上面的代码不理解“this”是什么,因为它在 addListener 函数中。我如何使它工作?

标签: google-mapsvue.js

解决方案


添加一个变量引用this应该可以工作:

const self = this
this.directionsRenderer.addListener('directions_changed', 
     function() {
         self.computeTotalDistance()  // I need this to be a called when the direction change
      }
)

推荐阅读