我正在尝试从另一个方法调用一个方法,为此我使用了它。但是我的控制台导致我出错。
如何在 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/