来自(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()
打印得到
再次感谢