vue.js - VueJs this.method 不是函数?如何在 Vuejs 中的另一个方法中调用一个方法?

标签 vue.js google-maps-api-3

我正在尝试从另一个方法调用一个方法,为此我使用了它。但是我的控制台导致我出错。

如何在 Vuejs 中调用另一个方法中的方法?

代码

 methods: {
     searchLocations: function() {
         var address = this.search
         var geocoder = new window.google.maps.Geocoder()
         geocoder.geocode({
             address: address
         }, function(results, status) {
             if (status === window.google.maps.GeocoderStatus.OK) {
                 this.buscarLojas(results[0].geometry.location)
             }
         })
     },
     buscarLojas: function(center) {
         console.log(center)
     }
 }

控制台:

this.buscarLojas is not a function

最佳答案

你有一个覆盖 this 关键字的匿名回调函数,你可以在使用它之前将 this 分配给另一个变量 ref匿名函数:

methods: {
    searchLocations: function () {
      var address = this.search
      var geocoder = new window.google.maps.Geocoder()
      var ref = this
//    ^^^^^^^^^^^^^^
      geocoder.geocode({address: address}, function (results, status) {
        if (status === window.google.maps.GeocoderStatus.OK) {
          ref.buscarLojas(results[0].geometry.location)
        //^^^
        } else {
          alert(address + ' not found')
        }
      })
    },
    buscarLojas: function (center) {
      console.log(center)
    }
}

或者使用箭头函数:

methods: {
    searchLocations: function () {
      var address = this.search
      var geocoder = new window.google.maps.Geocoder()
      geocoder.geocode({address: address}, (results, status) => {
      //                                                     ^^
        if (status === window.google.maps.GeocoderStatus.OK) {
          this.buscarLojas(results[0].geometry.location)
        } else {
          alert(address + ' not found')
        }
      })
    },
    buscarLojas: function (center) {
      console.log(center)
    }
}

关于vue.js - VueJs this.method 不是函数?如何在 Vuejs 中的另一个方法中调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51289458/

相关文章:

javascript - 从折线坐标数组创建高程剖面

javascript - Google Maps API 标记聚类器更改级别大小

vue.js - Vue CLI + Webpack : I need a separate css file from a single scss

vue.js - 如何在vue.config.js中忽略Vue CLI 3上的插件

javascript - 为什么这个 vue 转换没有达到预期效果?

javascript - 为什么标记标题不显示在我的 Google Maps API3 应用程序中?

javascript - Materialise js 在第一次加载时不起作用

javascript - vue.js 使用计时器自动重新加载/刷新数据

javascript - 为什么当我第二次点击 Google Maps JavaScript 时,它没有正确显示 map ?

javascript - 使用 jQuery 下拉菜单更改谷歌地图图标