uniapp瀑布流h5(一行代码解决)

2,395 阅读1分钟

链接

先贴链接吧:ext.dcloud.net.cn/plugin?id=2…

前言

自定义瀑布流组件,用法很简单,一行代码就可以搞定。自定义布局,不需要使用固定模板~

用法

1.引入组件

  import flowLayout from "@/components/eiml-flow/eiml-flow.vue"
  export default {
        components:{
            'flowLayout':flowLayout
        },

2.使用组件

<flowLayout :columnNum="2">
  <!-- 此处写循环布局就可以了,需要注意 :slot="index" 必须这么写,因为空间内,是通过它来展示的 -->
  <view v-for="(item,index) in list" v-bind:key="index" :slot="index">
  </view>
</flowLayout>

效果预览

原理解析

利用vue中的slot在瀑布流布局中选择性展示并重新排版。

由于微信小程序阉割了slot功能,所以目前只能h5来使用~

1.预加载容器

想要写出一个简单且通用的组件出来,就需要有所牺牲~此代码便是预加载,先在该容器中渲染出整个界面,渲染出来后,才能准确的拿到控件的高度。

childCount:所有的slot数量

		<scroll-view style="width: 0rpx;height: 0rpx;">
			<view v-for="(item,index) in childCount" v-bind:key="index">
				<slot :name="index"></slot>
			</view>
		</scroll-view>

2.显示布局

上面是隐藏起来的布局,下面是真正展示的布局。

columnWidth:根据列的多少计算出每一列的宽度

tabList:所有的列

itemTab:列的索引

根据name来选择性展示内容

		<view class="column" :style="{'width':columnWidth+'%'}"
			v-for="(itemTab,indexTab) in tabList" v-bind:key="indexTab">
			<view v-for="(item,index) in itemTab" v-bind:key="index">
				<slot :name="item"></slot>
			</view>
		</view>

3.分配内容

先拿到所有slot的总数,先让预加载内容加载出来

this.childCount=Object.getOwnPropertyNames(this.$slots).length;

等待预加载内容加载完成后,再去对内容进行排列

var that=this;			
this.$nextTick(function(){		
    that.refreshList();//进行内容排列		
});