项目有设计这个板块,网上搜了一下发现对应博客已经很老了,官方文档也没有匹配对应介绍,
我这里设计的是通过用户IP获取当前所在地区,再通过所在地区获取当地天气,其中的参数什么的详情请见官方文档,我这里只用了城市,天气,温度,风向的参数。
created() {
const that = this;
const token = getToken();
if (this.userIp === "") {
getIp(token).then((res) => {
this.userIp = res.ip;
console.log(this.userIp);
const userInput = this.userIp;
const apiKey = "和风控制台有自己的api";
const apiURL = `https://geoapi.qweather.com/v2/city/lookup?location=${userInput}&key=${apiKey}`;
console.log("apiURL", apiURL);
fetch(apiURL)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
if (data.code === "200") {
this.location = [...data.location];
if (this.location[0].id !== "") {
const Id = this.location[0].id;
console.log("this.location", Id);
const apiURL2 = `https://devapi.qweather.com/v7/weather/now?location=${Id}&key=${apiKey}`;
console.log("apiURL2", apiURL2);
fetch(apiURL2)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
console.log("data", data);
if (data.code === "200") {
that.weather = data.now;
console.log(that.weather);
} else if (data.code === "404") {
this.$message("当前地区天气数据暂无");
} else {
// throw new Error("API returned error code: " + data.code);
}
})
.catch((error) => {
console.error("获取城市天气时发生错误:", error);
});
}
} else if (data.code === "404") {
this.$message("当前地区天气数据暂无");
} else {
// throw new Error("API returned error code: " + data.code);
}
})
.catch((error) => {
console.error("获取城市ID时发生错误:", error);
});
// setTimeout(() => {
// }, 200);
});
}
},
这里因为和风天气的链接原因,所以我选择使用fetch,但是还有一个很重要的点就是return response.json(); 这一步代码