小程序列表组件图片懒加载

2019-09-27  本文已影响0人  w龙

父组件

##wxml部分
<view>
    <goodsList goodsList="{{list}}" id="list" listIndex="{{listIndex}}"/>
</view>
//js部分
Page({
  data: {
     count:50,
     list:[],
  },
  onLoad: function (options) {
    this.getList()
  },
  getList(){
    let obj = {
      sceneId: 3,
      returnCount: this.data.count
    }
    app.fetch(app.globalData.url + '/mobile/index.php?act=index&op=indexAirecRecommendList&t=json', obj, 'POST', 'application/json').then(res=>{
      let list = res.data.data.goods_list;
      list = list.map((n,i)=>{
        n.goods_image_url=`${n.goods_image_url}!j360`  //阿里数据图片截图
       //前6个列表图片不需要懒加载,页面出来就要渲染,所以就不用添加show为false
        n.show = i > 5 ? false : true
        return n
      })
      this.setData({
        list
      })
    })
  },
  onPageScroll() { // 滚动事件
    this.selectComponent("#list").scroll();
  }
})

子组件

//wxml部分
    <view class="goods-list-content">
        <block wx:for="{{goodsList}}" wx:key="index">
            <view class="items items-{{index}} goods-list-content-item">
                <view class="pic_content">
                    <image  bindtap="toDetail"
                        style="width: 100%; height: 339rpx;" mode="aspectFill"
                      class="{{item.show ?'Action':''}}" 
                      src="{{ item.show ? item.goods_image_url :'' }}"/>
                </view>
                <view class="goods-list-content-item-msg">
                    {{item.goods_name}}
                </view>
            </view>
        </block>
    </view>
//wxss部分
image {
  opacity: 0;
  transition: opacity 0.3s linear 0.3s;
}
image.Action{
  opacity: 1;
}
//js部分
const app = getApp();
Component({
      properties: {
        goodsList: {
          type: Array,
          value: []
        }
      },
     data: {windowHeight :0},
     attached (){
       this.data.windowHeight=wx.getSystemInfoSync().windowHeight
      },
      methods: {
        scroll() {
          this.showImg()
        },
        showImg() {
          let group = this.data.goodsList
          let height = this.data.windowHeight // 页面的可视高度
          const query = wx.createSelectorQuery().in(this)
          query.selectAll('.items').boundingClientRect(ret => {
            ret.forEach((item, index) => {
              if (item.top <= height) {
                group[index].show = true // 根据下标改变状态
              }
            })
            this.setData({
              goodsList: group
            })
          }).exec()
        }
      }
})
上一篇下一篇

猜你喜欢

热点阅读