小程序开发系列(三)数据交互与渲染

微信小程序的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.如下

{{item.no}}({{item.content}})


/**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; }

最终的呈现效果

小程序开发系列(三)数据交互与渲染
文章图片


【小程序开发系列(三)数据交互与渲染】转载请注明出处




    推荐阅读