前兩天寫了關于組件庫 iView Weapp的教程,其實也就是把文檔上的例子拿出來體驗了一遍,今天寫一個具體的例子,調用一個免費的天氣接口的api,并且把所獲取的內容展示在前端的界面,前端界面與 iView Weapp結合,展示的一個小的demo.
先上效果
開始寫代碼:
1:找打一個免費的天氣接口
免費接口api:
https://www.apiopen.top/api.html#top
https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7
2:寫js代碼
寫一個request請求,把準備好的天氣接口放在url里面,當請求成功的時候,在控制臺打印一下返回的res.data數據
wx.request({url: 'https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7',header: {'content-type': 'application/json'},success: res => {console.log(res.data)}})
這個時候可以看到控制臺已經有打印了接口數據了
3:接收到了數據之后,是對數據進行處理
在請求接口成功之后,用setData接收數據,并且需在data中聲明一個接收數據的變量。
4:js寫完之后,現在開始寫wxml里面的內容,將數據渲染在界面
前面說用的是組件庫 iView Weapp,樣式可以自己選擇,我這里選了一個卡片。
在使用組件的時候,需要在json里面引入一下:
https://weapp.iviewui.com/components/card
將里面的代碼復制過來,放在wxml,并且根據改成自己需要的。
<view class='list-li mflex' wx:for="{{list.forecast}}" wx:key="index"><i-card style="margin: 0px; padding: 0px; outline: none; line-height: 25.2px; font-size: 14px; width: 660px; overflow: hidden; clear: both; font-family: tahoma, arial, "Microsoft YaHei";">{"usingComponents": {"i-card": "../../dist/card/index"}}
js:
Page({data: {list: []},onLoad: function (options) {wx.request({url: 'https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7',header: {'content-type': 'application/json'},success: res => {console.log(res.data)this.setData({//第一個data為固定用法,第二個data是json中的datalist: res.data.data})}})},})
wxml:
<view class='list-li mflex' wx:for="{{list.forecast}}" wx:key="index"><i-card title="{{list.city}}天氣" extra="{{list.city}}" thumb="https://i.loli.net/2017/08/21/599a521472424.jpg"><view slot="content">{{item.date}} {{item.high}} {{item.low}} </view><view slot="footer">{{list.ganmao}}</view></i-card></view>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
|
新聞熱點
疑難解答