我在尝试从应用程序的其他方法内部调用方法时遇到Vue方法调用错误:
JS:
implementation 'com.google.firebase:firebase-inappmessaging-display:17.0.3'
这是html:
const app = new Vue({
el: '#info',
data() {
return {
position: {},
areas: {}
};
},
ready() {
},
mounted() {
},
methods: {
prepareComponent(){
},
loadContent(){
console.log(this.position);
let queryString = '?lat='+this.position.coords.latitude+'&lon='+this.position.coords.longitude;
axios.get('/api/getarea'+queryString)
.then(response => {
this.areas = response.data;
this.showAreaData();
});
},
showAreaData(){
var cities = [];
for(var area of this.areas){
cities.push(area.city);
}
console.log(cities);
},
getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.position = position;
this.loadContent();
}, function(error) {
console.log(error);
});
}
},
},
});
运行代码后,我得到一个未定义loadContent的错误(TypeError:this.loadContent不是函数)。 我在这里想念什么?
答案 0 :(得分:2)
尝试添加var _this= this;
使用_this.loadContent();
或使用app.loadContent();
getLocation(){
var _this= this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.position = position;
_this.loadContent();
}, function(error) {
console.log(error);
});
}
},
答案 1 :(得分:1)
this
是指调用函数的对象。在当前情况下,这是navigator.geolocation
。您可以通过在函数上调用bind
来覆盖调用对象:
getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.position = position;
this.loadContent();
}.bind(this), function(error) {
console.log(error);
});
}
}