【发布时间】:2018-06-28 22:46:45
【问题描述】:
我正在尝试使用 axios 从 openweathermap 获取数据,目前,我正在通过使用一些方法从用户浏览器获取 lat 和 lon,然后调用构建 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,所以我不确定我在这里做错了什么。我还尝试在getWeather 函数中添加let self = this; 并将所有this 替换为self,但这不起作用。
问题是我正在尝试从 apiUrl 获取 URL,该 URL 应该由 getUrl 方法更新。虽然在安装后运行getWeather 时,url 似乎没有更新(如果它的硬编码它工作正常)。
感谢您的帮助。
【问题讨论】:
标签: javascript vue.js axios