赞
踩
天气查询是一个简单的HTTP接口,根据用户输入的adcode,查询目标区域当前/未来的天气情况,数据来源是中国气象局。
如无特殊声明,接口的输入参数和输出数据编码全部统一为UTF-8。
- import axios from 'axios';
- import Skycon from 'vue-skycons';
- export default {
- components: { Skycon },
- data() {
- return {
- key: 'ef51caedee9eccc60accb02fcb8*****', //自己的key,建议自己申请
- weather: {}, //用于存放天气相关的数据
- iconCondition: null, //icon值
- }
- },
- mounted() {
- this.getLocationInfo();
- },
- <!--天气系统-->
- <div class="flex-center" style="margin-left: 650px; cursor: pointer;"
- @click="navTo('https://weather.cma.cn/web/weather/57516.html')">
-
- <div style="height: 60px; margin-top: -40px; margin-right: 6px;">
- <div style="height: 25px;">{{ formatDate(weather) }} </div>
- <div style="height: 25px; font-weight: bold; font-size: 20px; margin-left: 5px; color: Orange;">{{
- weather.city }}</div>
- </div>
- <skycon v-if="iconCondition" :condition="iconCondition" color="CornflowerBlue" size="40" />
- <div v-if="iconCondition" class="flex-center font-22" style="margin-left: 6px;">
- <span style="color: MediumTurquoise; margin-right: 6px;">{{ weather.temperature }}℃ </span>
- <span>{{ weather.weather }}</span>
- </div>
-
- </div>

- methods: {
- // 获取用户位置信息
- async getLocationInfo() {
- const params = {
- key: this.key,
- };
- const { data } = await axios.get('https://restapi.amap.com/v3/ip', { params });
- // data.adcode值为获取天气需要的city值
- this.getWeather(data.adcode);
- },
- // 获取天气详情
- async getWeather(adcode) {
- const params = {
- key: this.key,
- city: adcode,
- };
- const { data } = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo`, { params });
- this.weather = data.lives[0];
- this.iconCondition = this.setWeatherIcon(data.lives[0]?.weather);
- },
- //设置时间只显示年月日
- formatDate(weather) {
- const date = new Date(weather.reporttime);
- const year = date.getFullYear();
- const month = (1 + date.getMonth()).toString().padStart(2, '0');
- const day = date.getDate().toString().padStart(2, '0');
- return `${year}-${month}-${day}`;
- },
- // 设置icon
- setWeatherIcon(weather) {
- // 只处理了基础的天气,可以继续精细化处理
- if (weather === '晴') {
- return 'clear-day';
- } else if (weather.includes('云')) {
- return 'partly-cloudy-day';
- } else if (weather.includes('风')) {
- return 'wind';
- } else if (weather.includes('雨')) {
- return 'rain';
- } else if (weather.includes('雪')) {
- return 'snow';
- } else if (weather.includes('雾')) {
- return 'fog';
- }
- return 'cloudy';
- },
- }

到这里页面上就会显示出一个很好看的实时定位的天气小组件啦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。