微信小程序,首页加载和触底翻页,功能分离后职责更清晰

236 阅读1分钟

以前的做法是把翻页融到getList()里,进行相应的逻辑判断。

现在的做法是:getList()负责加载第1页,翻页的工作交给pageNext()来做,分工更明确,职责更清晰。

直接上代码

<van-cell-group border="{{false}}">
  <block wx:for="{{sensorList}}" wx:key="index">
  <van-cell is-link="{{assetId != 0}}" center use-label-slot bindtap="doEdit" data-name="{{item.name}}" data-id="{{item.deviceId}}" data-team="{{item.team}}" data-worktype="{{item.worktype}}" data-status="{{item.status}}" data-phone="{{item.phone}}" data-type="2">
    <view slot="title">
      <view class="gatewayName" wx:if="{{assetId != 0}}">{{item.name}} <text class="status{{item.active}}">{{item.active == 0? '不在网': '在网'}}</text></view>
    </view>
    <view slot="label" class="label">
      <view><text wx:if="{{assetId != 0}}">ID: </text>{{item.deviceName}} </view>
      <view wx:if="{{assetId != 0}}">{{item.workerType}} {{item.team}} {{item.phone}}</view>
    </view>
  </van-cell>
  </block>
</van-cell-group>
<van-divider contentPosition="center" hairline wx:if="{{isBottom}}">只有这么多了</van-divider>
import {
  catchError,
  getDevices
} from '../../../common/api'

const app = getApp()
Page({

  data: {
    sensorList: [],
    page: 1,
    isBottom: false,
    assetId: 0
  },

  onLoad: function (options) {
    this.getList()
  },

  getList: function () {
    const xheaders = app.globalData.xheaders
    let sensorList
    let params = {}
    params.page = 1
    getDevices(params, xheaders).then(res => {
      gatewayList = res.data
    }).catch(res => {
      catchError(res, '列表加载失败')
    })
    this.setData({
      sensorList
    })
  },

  pageNext: function(){
    let _this = this
    let page = _this.data.page + 1
    let params = {}
    params.page = page
    const xheaders = app.globalData.xheaders
    getDevices(params, xheaders).then(res => {
      let list = _this.data.sensorList.concat(res.data)
      _this.setData({
        page: page,
        sensorList: list,
        isBottom: res.data.length == 0 ? true : false
      })
    }).catch(res => {
      catchError(res, '列表加载失败')
    })
  },

  onReachBottom: function(){
    if(!this.data.isBottom){
      this.pageNext()
    }
  }

})
{
  "usingComponents": {
    "van-cell": "@vant/weapp/cell/index",
    "van-cell-group": "@vant/weapp/cell-group/index",
    "van-divider": "@vant/weapp/divider/index"
  },
}