今天写了一个天气组件效果如下:
实现代码如下:
<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>