在vue中调用和风天气城市与天气api
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
·
项目有设计这个板块,网上搜了一下发现对应博客已经很老了,官方文档也没有匹配对应介绍,
我这里设计的是通过用户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(); 这一步代码
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:3 个月前 )
9e887079
[skip ci] 1 年前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)