vue调用和风天气api(class类)

本文介绍了如何在Vue项目中调用和风天气API获取天气数据,包括使用class定义模块,通过async/await处理异步请求,获取城市ID并基于此获取7天天气预报。示例代码展示了完整的调用流程和关键步骤。
摘要由CSDN通过智能技术生成

来自(12条消息) Vue调用和风天气API(详细步骤,含源码)_苼歌己沫的博客-CSDN博客

官网有问题,使用       https://devapi.qweather.com

感谢博主

定义class类

class weather{
  constructor(options){
    this.city = '你自己的城市';
    this.daily=null;
    this.key = '你自己的key';
  }
  async searchWeather(){//注意:这里有 async 用来完成异步操作
    //由于调用api是异步操作
    //在请求的时候需要用async+await让它同步,否则数据不好取出
    //如果没有await返回的是一个Promise 对象,我学术短浅,暂时没学到,不会取

    //获取城市的ID
    let httpUrl = `https://geoapi.qweather.com/v2/city/lookup?location=${this.city}&key=${this.key}`
    let res = await fetch(httpUrl)
    let result = await res.json()
    let id = result.location[0].id
    //根据城市id获取具体的天气(7天)https://api.qweather.com/v7/weather/7d?[请求参数]
    let httpUrl1 = `https://devapi.qweather.com/v7/weather/7d?location=${id}&key=${this.key}`
    let res1 = await fetch(httpUrl1)
    let result1 = await res1.json()
    // console.log(result1)
    this.daily=result1.daily
  }
}
export default weather;

导入

import weather from "@/class/weather"

异步调用

async function main(){
      let Weather=new weather({})
      await Weather.searchWeather()
      console.log(Weather.daily)
    }
    main()

打印得到

再次感谢 

苼歌己沫

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值