我正试图从另一个方法中调用一个方法,为此我使用了它。但是我的控制台导致我出错。
如何在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不是函数
答案 0 :(得分:4)
您有一个覆盖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)
}
}
答案 1 :(得分:0)
使用箭头函数进行回调
geocoder.geocode({address: address}, (results, status) => {
if (status === window.google.maps.GeocoderStatus.OK) {
this.buscarLojas(results[0].geometry.location)
}
})
答案 2 :(得分:0)
我知道这里已经有答案了,但这也可以是一个方便的选择
methods: {
var self = this; //this line will take control of **this** which can be use later
searchLocations: function() {
var address = self.search
var geocoder = new window.google.maps.Geocoder()
geocoder.geocode({
address: address
}, function(results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
self.buscarLojas(results[0].geometry.location)
}
})
},
buscarLojas: function(center) {
console.log(center)
}
}