微信小程序 數據交互與渲染
實現效果圖:

微信小程序的api中提供了網絡交互的api,我們只要調用即可和后端進行數據交互,該api為wx.request.,具體代碼如下。
//list.js //獲取應用實例 var app = getApp() Page({ data: { list:[], hiddenLoading: true, url: '' }, loadList: function () { var that = this; that.setData({ hiddenLoading: !that.data.hiddenLoading }) var url = app.urls.CloudData.getList; that.setData({ url: url }); wx.request({ url: url, data: {}, method: 'GET', success: function (res) { var list= res.data.list; if (list == null) { list = []; } that.setData({ list: list, hiddenLoading: !that.data.hiddenLoading }); wx.showToast({ title: "獲取數據成功", icon: 'success', duration: 2000 }) }, fail: function (e) { var toastText='獲取數據失敗' + JSON.stringify(e); that.setData({ hiddenLoading: !that.data.hiddenLoading }); wx.showToast({ title: toastText, icon: '', duration: 2000 }) }, complete: function () { // complete } }), //事件處理函數 bindViewTap: function () { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function () { }, onReady: function () { this.loadList(); }, onPullDownRefresh: function () { this.loadList(); wx.stopPullDownRefresh() } }) 在loadList函數中進行了網絡請求,請求的數據放到了data的list中。我們使用setData來修改list,在該函數調用之后,微信小程序的框架就會判斷數據狀態的變化,然后進行diff判斷,如果有變化就渲染到界面中。這個與react.js的渲染方式相似,主要是內部維護了一個類似于虛擬文檔的對象,然后通過對虛擬文檔的判斷來呈現界面,這樣可以大大提高性能。
這里我們還做了一個下拉刷新的觸發,即onPullDownRefresh函數,為了能夠使用下拉刷新,我們需要進行配置,現在我們只需要當前頁面生效,所以只要在對應頁的json中配置即可,即在list.json中配置。
list.json
{ "navigationBarTitleText": "產品列表", "enablePullDownRefresh":true } 如果需要所有的頁面的生效,可以在app.json中的window中配置。
app.json
{ "pages":[ "pages/index/index", "pages/logs/logs", "pages/list/list" ], "window":{ "backgroundTextStyle":"light", "navigationBarBackgroundColor": "#fff", "navigationBarTitleText": "WeChat", "navigationBarTextStyle":"black", "enablePullDownRefresh":true } } 在app.json中,還有一個pages,我們需要路由的頁面都需要在這里注冊,否則無法路由到。
在請求數據的時候,加入了等待和獲取成功失敗的提示。這需要相應的頁面配合,頁面代碼list.wxm.如下
<!--list.wxml--> <view class="container container-ext"> <!--默認隱藏--> <loading hidden="{{hiddenLoading}}">正在加載</loading> <scroll-view scroll-y="true"> <view> <block wx:for="{{list}}" wx:key="no"> <view class="widget"> <view> <text >{{item.no}}({{item.content}})</text> </view> </view> </block> </view> </scroll-view> </view> /**list.wxss**/ .widget { position: relative; margin-top: 5rpx; margin-bottom: 5rpx; padding-top: 10rpx; padding-bottom: 10rpx; padding-left: 40rpx; padding-right: 40rpx; border: #ddd 1px solid; } /**app.wxss**/ .container { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: space-between; box-sizing: border-box; padding-top: 10rpx; padding-bottom: 10rpx; } 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答