微信小程序—天气预报查询
发现了一个免费的天气接口
天气接口api 地址:http://wthrcdn.etouch.cn/weather_mini?city=城市名称
(1)index.wxml文件
<!--index.wxml--> <view class="page"> <!-- top部分 --> <view class="top"> <input placeholder="输入城市名进行搜索" bindinput="bindKeyInput"></input> <view class="icon"> <icon type="search" size="25" bindtap="search" /> </view> </view> <!-- body部分 --> <view class="body"> <view class="city"> <text>{ {city}}</text> </view> <view class="today"> <text>{ {date}}</text> </view> <view> <image src="{ {pic}}" mode="aspectFit" style="width: 400rpx; height: 400rpx" /> </view> </view> <!-- bottom部分 --> <view class="bottom"> <view class="weather"> <text>{ {weather}}</text> </view> <view class="right"> <view class="temp"> <text>{ {temp}}</text> </view> <view class="wind"> <text>{ {wind}}</text> </view> </view> </view> </view>
(2)index.wxss文件
/**index.wxss**/ page { background-color: #5a9cd8; color: #fff; } .page { margin: 50rpx; } .top { display: flex; padding: 20rpx; flex-direction: row; background-color: #efefef; position: relative; margin-bottom: 20rpx; border-radius: 10rpx; } .input { width: 80%; font-size: 32rpx; } .icon { width: 10%; position: absolute; right: 0; bottom: 5rpx; } .body { text-align: center; display: flex; flex-direction: column; } .city { font-size: 80rpx; } .today { font-size: 34rpx; } .bottom { display: flex; flex-direction: row; align-items: center; text-align: center; } .weather { font-size: 38rpx; width: 50%; } .right { display: flex; flex-direction: column; } .wind { font-size: 40rpx; } .temp { font-size: 40rpx; font-weight: bold; font-family: Arial, Helvetica, sans-serif; } input { color: #333; }
(3)index.js文件
主要是实现三个动作
一个是初始化加载
一个是动态获取input的城市名称
一个是绑定搜索按钮,实现搜索功能
当然,最关键的是weather函数,用来将给.wxml页面中所需的天气数据赋值
// index.js // 定义城市、天气、温度、风级、图片,日期参数 var defaultcity, getweather, gettemp, getwind, getpic, getdate var vurl = http://wthrcdn.etouch.cn/weather_mini?city= Page({ data: {}, // 初始化加载 onLoad: function (e) { // 默认城市名称 defaultcity = 长沙 this.weather() }, // 动态获取input输入值 城市名称 bindKeyInput: function (e) { defaultcity = e.detail.value }, // 搜索城市 search: function (e) { this.weather() }, weather: function () { wx.showLoading({ title: 加载中, }) wx.request({ url: vurl + defaultcity, success: res => { console.log(res.data) if (!res.data) { console.log(获取天气接口失败) return } getweather = res.data.data.forecast[0].high + + res.data.data.forecast[0].low gettemp = res.data.data.forecast[0].high getwind = res.data.data.forecast[0].fengxiang + , + res.data.data.forecast[0].fengli.replace(/<![CDATA[(.*)]]>/, $1) getpic = getdate = res.data.data.forecast[0].date this.setData({ city: defaultcity, weather: getweather, temp: gettemp, wind: getwind, pic: getpic, date: getdate }) wx.hideLoading() } }) } })
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信公众号推送模板消息