Javascript Vue方法无法从其他方法内部工作
在尝试从应用程序的其他方法内部调用方法时,出现Vue方法调用错误: JS:Javascript Vue方法无法从其他方法内部工作,javascript,vue.js,methods,Javascript,Vue.js,Methods,在尝试从应用程序的其他方法内部调用方法时,出现Vue方法调用错误: JS: const app = new Vue({ el: '#info', data() { return { position: {}, areas: {} }; }, ready() { }, mounted() { }, methods: { prepareComponent(){ }, loadContent(){ consol
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);
});
}
},
},
});
以下是html:
<div id="info">
<a href="#" id="getPosition" class="btn btn-link" @click="getLocation">Get Position</a>
<ul>
</ul>
</div>
运行代码后,我得到一个错误,loadContent没有定义(TypeError:this.loadContent不是一个函数)。
我在这里遗漏了什么?尝试添加
var\u this=this代码>使用\u this.loadContent()代码>
或者使用app.loadContent()代码>
尝试添加var\u this=this代码>使用\u this.loadContent()代码>
或者使用app.loadContent()代码>
此
引用调用函数的对象。在本例中,这是navigator.geolocation
。您可以通过调用函数上的bind
来覆盖调用对象:
getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.position = position;
this.loadContent();
}.bind(this), function(error) {
console.log(error);
});
}
}
此
引用调用函数的对象。在本例中,这是navigator.geolocation
。您可以通过调用函数上的bind
来覆盖调用对象:
getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.position = position;
this.loadContent();
}.bind(this), function(error) {
console.log(error);
});
}
}
啊,谢谢我太累了,也许这就是为什么我错过了这样一件基本的事情。啊,谢谢。)我太累了,也许这就是为什么我错过了这样一件基本的事情。