今天寫了一個天氣組件效果如下:
實現代碼如下:
<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>