在vue中调用和风天气城市与天气api

项目有设计这个板块,网上搜了一下发现对应博客已经很老了,官方文档也没有匹配对应介绍,

我这里设计的是通过用户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(); 这一步代码

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值