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

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

微信小程序的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;
}
最终的呈现效果


作者:学而时习之
来源:CSDN
原文:https://blog.csdn.net/xxdddail/article/details/54574757
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值