js获取天气信息

6 篇文章 0 订阅

效果如下
在这里插入图片描述

调用接口http://wthrcdn.etouch.cn/weather_mini?city=地址
注意:使用axios会直接请求失败,这边使用了jq的ajax
(原因大概是axios没配置dataType: “text”)
请求出来的是gzip格式,会显示乱码,下方代码即可获取天气

//vue代码
      <div class="weather" v-if="weather">
        <img
          src="@/assets/dytop.png"
          class="weatherPic"
          v-if="weather.type == '多云'"
        />
        <img
          src="@/assets/rainT.png"
          class="weatherPic"
          v-else-if="
            weather.type == '小雨' ||
            weather.type == '中雨' ||
            weather.type == '大雨' ||
            weather.type == '暴雨'||
            weather.type == '阵雨'||
            weather.type == '雷阵雨'||
            weather.type == '暴雨'||
            weather.type == '大暴雨'||
            weather.type == '特大暴雨'
          "
        />
        <img
          src="@/assets/snowT.png"
          class="weatherPic"
          v-else-if="
            weather.type == '小雪' ||
            weather.type == '中雪' ||
            weather.type == '大雪' ||
            weather.type == '雨加雪'||
            weather.type == '暴雪'
          "/>
        <img
          src="@/assets/sunT.png"
          class="weatherPic"
          v-else-if="
            weather.type == '晴' ||
            weather.type == '晴天'
          "
        />
        <img
          src="@/assets/cloudyT.png"
          class="weatherPic"
          v-else-if="weather.type == '阴'"
        />
        <span class="weatherText">{{weatherText}}</span>
      </div>

		//js代码
	<script>
	import $ from "jquery";
	export default {
	 data() {
	    return {
	      weather: null,
	      weatherText: null,
	     }
     	},
     	mounted: function () {
     	var _this = this;
			$.ajax({
			  method: "GET",
			  url: "http://wthrcdn.etouch.cn/weather_mini?city=焦作",
			  headers: {
			    Accept: "application/json; charset=utf-8",
			  },
			  dataType: "text",
			  success: function (result, status) {
			    _this.weather = JSON.parse(result).data.forecast[0];
			    // 去空格,抽离数字
			    var low = (
			      _this.weather.low.replace(/[^\d]/g, " ").trim() + "°"
			    ).trim();
			    var high = (
			      _this.weather.high.replace(/[^\d]/g, " ").trim() + "°C"
			    ).trim();
			    _this.weatherText = _this.weather.type + low + "~" + high;
			  },
			});
     	}
      }

	</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值