vue网页中的一个天气组件使用高德api

今天写了一个天气组件效果如下:

实现代码如下:

<template>
    <div>
      <span @click="getLocation" style="cursor: pointer">
        <span style="color:white;">{{ weatherInfo.area }}</span>
      </span> |
      <span style="color:white;">{{ weatherInfo.weather }}</span>
      
      <span style="color:white;font-weight: bold;">{{ weatherInfo.temperature }}°C</span> |
      <span style="color:white;">{{ weatherInfo.wind_direction }}</span>
      <span style="color:white;">{{ weatherInfo.wind_power }}</span>
      <!-- <img style="width:30px;vertical-align: middle;" :src="weatherInfo.weather_pic"/> -->
      <div v-if="isLoading" class="loading">加载中...</div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
  </template>

<script>
import {onLoad} from 'vue'
import axios from 'axios'
export default {
    data() {
        return{
            weatherInfo: {
                area: '郑州市',
                temperature: '34',
                weather: '多云',
                weather_pic: 'http://tianqiapi.com/static/img/icon/duoyun.png',
                wind_direction: '南风',
                wind_power: '3级',
                quality: '良'
            },
            errorMessage:'',
            isLoading:false
        };
    },
    created(){
        console.log('[DEBUG] 组件已挂载');
        this.getLocation();
    },
    methods: {
      async getLocation() {
        console.log('GetLocation');
           try {
                console.log('[DEBUG] 开始定位');
                const response = await axios.get('https://restapi.amap.com/v3/ip', {
                params: { key: 'your gaode api key' }
                });
                
                if (response.data.status === '1') {
                await this.getWeathData(response.data.city, response.data.adcode);
                } else {
                throw new Error(`定位失败: ${response.data.info}`);
                }
            } catch (error) {
                console.error('[ERROR] 定位异常:', error);
                this.errorMessage = '定位服务不可用';
                this.isLoading = false;
            }
        },
       async getWeathData(cityName, cityCode) {
            try {
                this.isLoading = true;
                const { data } = await axios.get('https://restapi.amap.com/v3/weather/weatherInfo', {
                params: {
                    key: 'your gaode api key',
                    city: cityCode,
                    extensions: 'base',
                    output: 'JSON'
                }
                });

                if (data.status === '1' && data.lives?.length > 0) {
                const weatherData = data.lives[0];
                // 安全更新数据
                this.weatherInfo = {
                    area: weatherData.city || cityName,
                    temperature: weatherData.temperature || '--',
                    weather: weatherData.weather || '未知',
                    wind_power: weatherData.windpower ? `${weatherData.windpower}级` : '--',
                    wind_direction: weatherData.winddirection ? `${weatherData.winddirection}风` : '--'
                };
                } else {
                throw new Error(data.info || '天气数据异常');
                }
            } catch (error) {
                console.error('[ERROR] 天气获取失败:', error);
                this.errorMessage = '天气数据获取失败';
                // 保留上次有效数据
            } finally {
                this.isLoading = false;
            }
        }
    }
}


  </script>
  
  <style scoped>
  span {
    margin: auto 3px;
  }
  
  .loading {
    font-size: 14px;
    color: #409eff;
    font-weight: bold;
  }
  
  .error-message {
    color: red;
    font-weight: bold;
    margin-top: 10px;
  }
  </style>
  
  

在使用的页面中引用该组件:

import weather from '@/views/weather/top-weather.vue'
 export default{
        components:{
            weather
        },
}

在页面嵌入该组件:

<div class="weather-layout">
                <weather/>
            </div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值