好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

小程序实现瀑布流动态加载列表

本文实例为大家分享了小程序实现瀑布流动态加载列表的具体代码,供大家参考,具体内容如下

最近业务需要做一个商城列表,就自己写了一个瀑布流来加载列表。

这个列表在很多地方都需要用到,就给写成组件,方便使用。

1、goodsBox.js代码

想法很简单,就是判断两列的高度,将数据插入低的一列。

let leftHeight = 0,
? rightHeight = 0; //分别定义左右两边的高度
let query;
Component({
? /**
? ?* 组件的属性列表
? ?*/
? properties: {
? ? goodsList: {
? ? ? type: Array,
? ? ? value: []
? ? },
? ? loadingShow: {
? ? ? type: Boolean,
? ? ? value: false
? ? },
? ? noInfoShow: {
? ? ? type: Boolean,
? ? ? value: false
? ? }
? },

? /**
? ?* 组件的初始数据
? ?*/
? data: {
? ? leftList: [],
? ? rightList: []
? },
? observers: {
? // 当goodsList发生变化时调用方法
? ? 'goodsList': function (goodsList) {
? ? ? this.isLeft()
? ? }
? },
? /**
? ?* 组件的方法列表
? ?*/
? methods: {
? ? async isLeft() {
? ? ? const {
? ? ? ? goodsList,
? ? ? ? leftList,
? ? ? ? rightList
? ? ? } = this.data;
? ? ? query = wx.createSelectorQuery().in(this);
? ? ? let list = goodsList.slice(leftList.length+rightList.length,goodsList.length)
? ? ? for (const item of list) {
? ? ? ? leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度,来觉得添加到那边
? ? ? ? await this.getBoxHeight(leftList, rightList);
? ? ? }
? ? ??
? ? },
? ? getBoxHeight(leftList, rightList) { //获取左右两边高度
? ? ? return new Promise((resolve, reject) => {
? ? ? ? this.setData({
? ? ? ? ? leftList,
? ? ? ? ? rightList
? ? ? ? }, () => {
? ? ? ? ? query.select('#left').boundingClientRect();
? ? ? ? ? query.select('#right').boundingClientRect();
? ? ? ? ??
? ? ? ? ? query.exec((res) => {
? ? ? ? ? ? leftHeight = res[0].height; //获取左边列表的高度
? ? ? ? ? ? rightHeight = res[1].height; //获取右边列表的高度
? ? ? ? ? ? resolve();
? ? ? ? ? });
? ? ? ? });
? ? ? })
? ? },
? }
})

这一块需要注意的是 wx.createSelectorQuery().in(this),将选择器的选取范围更改为自定义组件 component 内。微信文档.

2、goodsBox.wxml

这边主要就是把页面分成两列,一些css就不多写了

// wxml
<view class="box clearfix">
? <view id="left" class="left">
? ? <view class="shop_box" wx:for="{{leftList}}" wx:key="index" ></view>
? </view>
? <view id="right" class="right">
? ? <view class="shop_box" wx:for="{{rightList}}" wx:key="index" ></view>
? </view>
</view>
<view class="cu-load ?loading" wx:if="{{loadingShow}}"></view>
<view class="cu-load ?over" wx:if="{{noInfoShow}}"></view>

3、goodsBox.wxss

.left,.right{
? float: left;
}
.clearfix::after {
? content: ".";
? clear: both;
? display: block;
? overflow: hidden;
? font-size: 0;
? height: 0;
}
.clearfix {
? zoom: 1;
}

4、页面使用

现在json文件里面引用组件,然后使用组件

<goodsBox id="goodsBox" goodsList="{{goodsList}}" loadingShow="{{loadingShow}}" noInfoShow="{{noInfoShow}}"></goodsBox>

每次goodsList发生变化,组件就会调用瀑布流排列方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于小程序实现瀑布流动态加载列表的详细内容...

  阅读:31次