实时获取城市天气 前端 vue use

223 阅读1分钟

vue use 实时获取城市天气

import { ref, watch } from "vue";
import axios from "axios";
// 天气api 推荐 https://zhuanlan.zhihu.com/p/451158509 
// 城市LocationID映射表 https://github.com/qwd/LocationList/blob/master/China-City-List-latest.csv
const servers = new Map([
  [
    "高德",
    {
      api_url: "https://restapi.amap.com/v3/weather/weatherInfo",
      method: "GET",
      params: {
        city: "500000", // api参数文档 https://lbs.amap.com/api/webservice/guide/api/weatherinfo/
        key: "8faeeed25126b46ce6f9b1e6d31730f9",
      },
      data: {},
      handleRes(res) {
        // 对结果预处理
        const data = res.data["lives"][0];
        return {
          city: data.city,
          weather: data.weather,
          temperature: data.temperature,
        };
      },
    },
  ],
  [
    "心知天气",
    {
      api_url: "https://api.seniverse.com/v3/weather/now.json",
      method: "GET",
      params: {
        key: "S6_LHF3ecAhW3y0Xn", // api参数文档 https://seniverse.yuque.com/hyper_data/api_v3/nyiu3t?#%20%E3%80%8A%E5%A4%A9%E6%B0%94%E5%AE%9E%E5%86%B5%E3%80%8B
        location: "拉萨",
      },
      data: {},
      handleRes(res) {
        const data = res.data.results[0].now;
        console.log(data);
        return {
          weather: data.text,
          temperature: data.temperature,
        };
      },
    },
  ],
  [
    "和风天气",  // 暂时不可用 返回403
    {
      api_url: "https://api.qweather.com/v7/weather/now",
      method: "GET",
      params: {
        key: "2ab597141c774f96a29d6a0cb98d45fc", // 参数文档 https://dev.qweather.com/docs/api/weather/weather-now/
        location: "101140101",
      },
      data: {},
      handleRes(res) {
        console.log(res);
      },
    },
  ],
]);
const useWeather = (option = {}) => {
  const weather = ref({});
  // 默认间隔 4 小时请求一次
  const { type, params = {}, interval = 1000 * 60 * 4, handleRes } = option;
  if (!servers.has(type)) return new Error("type is Error");
  const serverConfig = servers.get(type);
  const preHandleRes = handleRes || serverConfig.handleRes; // 结果预处理函数
  const request = async () => {
    const res = await axios.request({
      url: serverConfig.api_url,
      method: serverConfig.method,
      params: {...serverConfig.params,...params},
    });
    weather.value = preHandleRes(res);
  };
  request();
  setTimeout(() => request(), 1000 * 60 * 4);
  return weather;
};
export default useWeather;

推荐使用自己去注册apikey,使用次数少的话,麻烦的话,直接使用吧就

import useWeather from "@/hooks/useWeather.js";
const weather = useWeather({
  type: "高德",
   params:{
    city:'540000',
    key: "8faeeed25126b46ce6f9b1e6d31730f9",
  }
});