vue项目中使用openweathermap获取天气

vue yekong 122℃

vue项目中使用openweathermap获取天气

数据可视化大屏项目开发中,需要显示天气,客户提供的是openweathermap平台的key,查询天气时需要使用到key 经纬度,这里将请求方式记录下来。

<!-- WeatherForecast.vue -->
<template>
  <div class="weather-forecast" v-if="weather.isLoaded">
    <img :src="weather.iconUrl" alt="天气图标">
    <span>{{ weather.description }}</span>
    <span>{{ weather.temp }}℃</span>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'WeatherForecast',
  setup() {
    const weather = ref({ 
      description: '', 
      temp: '', 
      iconUrl: '', 
      isLoaded: false 
    });

    const fetchWeather = async () => {
      try {
        const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {
          params: {
            lat: 32.0604, // 纬度
            lon: 110.7262, // 经度
            appid: 'your key',
            units: 'metric',
            lang: 'zh_cn'
          }
        });
        weather.value = {
          description: response.data.weather[0].description,
          temp: Math.round(response.data.main.temp),
          iconUrl: `http://openweathermap.org/img/w/${response.data.weather[0].icon}.png`,
          isLoaded: true
        };
      } catch (error) {
        console.error('获取天气信息失败:', error);
        weather.value.isLoaded = false;
      }
    };

    onMounted(() => {
      fetchWeather();
    });

    return {
      weather
    };
  }
}
</script>

<style lang="scss" scoped>
.weather-forecast {
  display: flex;
  align-items: center;

  img {
    width: 42px;
    margin-right: 10px;
  }

  span {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    margin-right: 20px;
    color: #aaccdd;
  }
}
</style>
喜欢 (0)