我正在尝试使用 axios 从 openweathermap 获取数据,目前,我正在通过使用几种方法从用户浏览器获取经纬度来构建 url,然后调用构建 url 的函数。
url 构建正确,没有任何问题,但是当我尝试使用 axios 调用 api 时,会发生奇怪的事情(基本上我得到了自己的页面 html 代码返回给我)
这是代码:
let weather = new Vue ({
el: '#weather',
data: {
error: '',
apiUrl: '',
city: '',
country: '',
icon: '',
description: '',
results: [],
},
methods: {
getPosition: function() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(this.getUrl);
}else{
this.error = 'Geolocation is not supported.';
}
},
getUrl: function(position){
let lat = position.coords.latitude;
let lon = position.coords.longitude;
this.apiUrl = buildWeatherUrl(lat, lon);
},
getWeather: function(){
axios.get(this.apiUrl).then(function (response) {
this.city = response.data.name;
this.results = response.data;
}).catch( error => { console.log(error); });
}
},
beforeMount() {
this.getPosition();
},
mounted() {
this.getWeather();
}
});
这是我第一次使用 Vue 和 axios,所以我不确定我在这里做错了什么。我还尝试添加 let self = this;
并将所有 this
替换为 getWeather
函数中的 self
但那没用。
问题是我正在尝试从 apiUrl
获取 url,该 url 应通过 getUrl
方法进行更新。尽管在安装后运行 getWeather
时,URL 似乎并未更新(如果其硬编码,则可以正常工作)。
感谢您的帮助。
请您参考如下方法:
我怀疑问题出在这一行navigator.geolocation.getCurrentPosition(this.getUrl);
。
当 this.getUrl
被 navigator
回调时,该函数不再具有正确的 this
,因此 this. apiUrl = buildWeatherUrl(lat, lon);
将不起作用。尝试将 this
绑定(bind)到 this.getUrl
,就像这样
getPosition: function() {
if (navigator.geolocation){
let getUrl = this.getUrl.bind(this)
navigator.geolocation.getCurrentPosition(getUrl);
}else{
this.error = 'Geolocation is not supported.';
}
},
或者简单地navigator.geolocation.getCurrentPosition(this.getUrl.bind(this));
此函数还有一个不正确的 this
。
axios.get(this.apiUrl).then(function (response) {
this.city = response.data.name;
this.results = response.data;
}).catch( error => { console.log(error); });
您需要重做之前的修复:
I also tried to add let self = this; and replace all this to self in the getWeather function but that didn't work.
或者简单地使用箭头函数。
axios.get(this.apiUrl).then(response => {
this.city = response.data.name;
this.results = response.data;
}).catch( error => { console.log(error); });
以下是有关如何管理 Javascript 的 this
的明确堆栈溢出答案的链接:https://stackoverflow.com/a/20279485/2498782
滚动到答案的标有“常见问题:使用对象方法作为回调/事件处理程序”的部分。