效果如下
调用接口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>