我正在使用VueJS和GoogleMaps在地图上执行操作。因此我写了这个功能设置:
methods: {
// Init GIS
init: function() {
initGISMap(this.$els.map);
},
updateGIS: function() {
getAutoCompletePlace(function(place){
searchMarker.setPosition(place.geometry.location);
autocompletePlace = place;
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
self.updateIncidentForm();
});
},
updateIncidentForm: function() {
console.log("UpdateIncidentForm");
getAddressComponents(function(components) {
this.autoCompleteAddress = components;
this.setIncidentAddressFields(components);
});
},
(...)
我想在updateIncidentForm
执行时调用getAutocompletePlace
函数。我在控制台中遇到的错误是:
bundle.js:11073 Uncaught TypeError:self.updateIncidentForm不是 功能
这很奇怪,因为它是代码中定义的函数?我需要以不同的方式调用函数吗?
答案 0 :(得分:3)
您在回调函数中调用self.updateIncidentForm()
,但实际上并未在任何地方定义变量self
。
据推测,你意味着写下类似的内容:
updateGIS: function() {
var self = this; // <--- you forgot this line!
getAutoCompletePlace(function(place){
// (irrelevant code omitted)
self.updateIncidentForm();
});
},
行var self = this
将对您调用updateGIS()
方法的对象的引用保存到本地变量self
中,以便您可以在传递给的匿名回调函数中使用它getAutoCompletePlace()
(其中this
的值会有所不同)。
bind()
来修复回调中this
的值,如下所示:
updateGIS: function() {
getAutoCompletePlace(function(place){
// (irrelevant code omitted)
this.updateIncidentForm();
}.bind(this));
},
回调函数定义locks the value of this
末尾的.bind(this)
回调到外部updateGIS()
函数中的值。