微信小程式 下拉刷新 上拉載入,簡單方便,易於上手。 1.首先上list.wxml代碼 2.再上js代碼 3.簡單的list.wxss 4.list.json配置文件 至此,一個簡單的下拉刷新上拉載入基本搞定了。巧用微信的各種Api,就很舒服。 繼續擴展的話: 1.updateDom那裡下拉刷新是簡 ...
微信小程式
下拉刷新 上拉載入,簡單方便,易於上手。
1.首先上list.wxml代碼
<!--pages/list/list.wxml-->
<view class="list-container">
<view class="header">
</view>
<view class="doc-item" wx:for="{{dataSource}}" wx:for-item="item" wx:key="{{item.id}}" bindtap='bindViewTap' data-url="{{item.url}}" data-name="{{item.name}}">
<text >{{item.title}}</text>
<view class='item-info'>
<text>{{item.author}}</text>
<text style='float: right'>{{item.time}}</text>
</view>
</view>
<view class="footer" wx:if="{{!hasMoreData}}">
沒有更多了
</view>
<view class="footer" wx:if="{{hasMoreData}}">
載入中...
</view>
</view>
2.再上js代碼
// pages/list/list.js
Page({
/**
* 頁面的初始數據
*/
data: {
id: "",
dataSource: [],
hasMoreData: true,
pageIndex: 1,
pageSize: 15,
isLoading: false
},
/**
* 生命周期函數--監聽頁面載入
*/
onLoad: function (options) {
this.setData({
id: options.id//從url上獲取id
})
wx.setNavigationBarTitle({title: options.nav})
this.getList(1)
},
getList: function(index){
wx.request({
url: 'your server url',
data: {
method: 'your method',
pageSize: this.data.pageSize,
pageIndex: index,
},
header: {
'content-type': 'application/json' // 預設值
},
success: (res) => {
if(this.data.pageIndex == 1){
wx.stopPullDownRefresh({
complete: this.updateDom(res)
})
}else{
this.updateDom(res)
}
}
})
},
updateDom: function(res){
this.setData({ dataSource: this.data.dataSource.concat(res.data.Data.List), isLoading: false })
if (this.data.pageSize > res.data.Data.Length) {
this.setData({ hasMoreData: false })
}
},
/**
* 生命周期函數--監聽頁面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函數--監聽頁面顯示
*/
onShow: function () {
},
/**
* 生命周期函數--監聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命周期函數--監聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函數--監聽用戶下拉動作
*/
onPullDownRefresh: function () {
if(!this.data.isLoading){
this.setData({ hasMoreData: true, pageIndex: 1, dataSource: [], isLoading: true})
this.getList(1)
}
},
//事件處理函數
bindViewTap: function (e) {
//To do somethiing
},
/**
* 頁面上拉觸底事件的處理函數
*/
onReachBottom: function () {
if(this.data.hasMoreData && !this.data.isLoading){
this.setData({ pageIndex: this.data.pageIndex + 1, isLoading: true})
this.getList(this.data.pageIndex)
}
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
}
})
3.簡單的list.wxss
/* pages/list/list.wxss */
page{
background-color: #E6E6E6;
}
.header{
text-align: center;
font-size: 14px;
color: #aaa;
}
.footer{
text-align: center;
padding-top: 36rpx;
padding-bottom: 48rpx;
font-size: 14px;
color: #aaa;
}
.doc-item{
padding: 24rpx 36rpx;
margin: 12rpx 0;
display: flex;
background: white;
flex-direction: column;
border-bottom: 1px solid #e3e3e3;
}
.item-info{
padding-top: 24rpx;
font-size: 14px;
color: #aaa;
}
4.list.json配置文件
{
"enablePullDownRefresh": true,
"backgroundTextStyle": "dark"
}
至此,一個簡單的下拉刷新上拉載入基本搞定了。巧用微信的各種Api,就很舒服。
繼續擴展的話:
1.updateDom那裡下拉刷新是簡單的清空重新載入,其實可以進行數組比較插入最新記錄;
2.出錯提示沒加;
3.可以使用騰訊開源框架Wepy這種現代化的類Vue框架進行組件化開發。