cl-waterfall.uvue 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <template>
  2. <view
  3. class="cl-waterfall"
  4. :class="[pt.className]"
  5. :style="{
  6. padding: `0 ${props.gutter / 2}rpx`
  7. }"
  8. >
  9. <view
  10. class="cl-waterfall__column"
  11. v-for="(column, columnIndex) in columns"
  12. :key="columnIndex"
  13. :style="{
  14. margin: `0 ${props.gutter / 2}rpx`
  15. }"
  16. >
  17. <view class="cl-waterfall__column-inner">
  18. <view
  19. v-for="(item, index) in column"
  20. :key="`${columnIndex}-${index}-${item[props.nodeKey]}`"
  21. class="cl-waterfall__item"
  22. :class="{
  23. 'is-virtual': item.isVirtual
  24. }"
  25. >
  26. <slot name="item" :item="item" :index="index"></slot>
  27. </view>
  28. </view>
  29. </view>
  30. </view>
  31. </template>
  32. <script setup lang="ts">
  33. import { assign, isNull } from "@/cool";
  34. import { computed, getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";
  35. import { parsePt } from "@/cool";
  36. defineOptions({
  37. name: "cl-waterfall"
  38. });
  39. // 定义插槽类型,item插槽接收item和index参数
  40. defineSlots<{
  41. item(props: { item: UTSJSONObject; index: number }): any;
  42. }>();
  43. // 组件属性定义
  44. const props = defineProps({
  45. // 透传属性
  46. pt: {
  47. type: Object,
  48. default: () => ({})
  49. },
  50. // 瀑布流列数,默认为2列
  51. column: {
  52. type: Number,
  53. default: 2
  54. },
  55. // 列间距,单位为rpx,默认为12
  56. gutter: {
  57. type: Number,
  58. default: 12
  59. },
  60. // 数据项的唯一标识字段名,默认为"id"
  61. nodeKey: {
  62. type: String,
  63. default: "id"
  64. }
  65. });
  66. // 获取当前组件实例的代理对象
  67. const { proxy } = getCurrentInstance()!;
  68. type PassThrough = {
  69. className?: string;
  70. };
  71. const pt = computed(() => parsePt<PassThrough>(props.pt));
  72. // 存储每列的当前高度,用于计算最短列
  73. const heights = ref<number[]>([]);
  74. // 存储瀑布流数据,二维数组,每个子数组代表一列
  75. const columns = ref<UTSJSONObject[][]>([]);
  76. /**
  77. * 获取各列的当前高度
  78. * 通过uni.createSelectorQuery查询DOM元素的实际高度
  79. * @returns Promise<> 返回Promise对象
  80. */
  81. async function getHeight(): Promise<void> {
  82. // 等待DOM更新完成
  83. await nextTick();
  84. return new Promise((resolve) => {
  85. // 创建选择器查询,获取所有列容器的边界信息
  86. uni.createSelectorQuery()
  87. .in(proxy)
  88. .selectAll(".cl-waterfall__column-inner")
  89. .boundingClientRect()
  90. .exec((rect) => {
  91. const nodes = rect[0] as NodeInfo[];
  92. if (!isNull(nodes)) {
  93. // 提取每列的高度信息,如果获取失败则默认为0
  94. heights.value = nodes.map((e) => e.height ?? 0);
  95. }
  96. resolve();
  97. });
  98. });
  99. }
  100. /**
  101. * 向瀑布流添加新数据
  102. * 使用虚拟定位技术计算每个项目的高度,然后分配到最短的列
  103. * @param data 要添加的数据数组
  104. */
  105. async function append(data: UTSJSONObject[]) {
  106. // 首先获取当前各列高度
  107. await getHeight();
  108. // 将新数据作为虚拟项目添加到第一列,用于计算高度
  109. columns.value[0].push(
  110. ...data.map((e) => {
  111. return {
  112. ...e,
  113. isVirtual: true // 标记为虚拟项目,会在CSS中隐藏
  114. } as UTSJSONObject;
  115. })
  116. );
  117. // 等待DOM更新
  118. await nextTick();
  119. // 延迟300ms后计算虚拟项目的高度并重新分配
  120. setTimeout(() => {
  121. uni.createSelectorQuery()
  122. .in(proxy)
  123. .selectAll(".is-virtual")
  124. .boundingClientRect()
  125. .exec((rect) => {
  126. // 遍历每个虚拟项目
  127. (rect[0] as NodeInfo[]).forEach((e, i) => {
  128. // 找到当前高度最小的列
  129. const min = Math.min(...heights.value);
  130. const index = heights.value.indexOf(min);
  131. // 将实际数据添加到最短列
  132. columns.value[index].push(data[i]);
  133. // 更新该列的高度
  134. heights.value[index] += e.height ?? 0;
  135. // 清除第一列中的虚拟项目(临时用于计算高度的项目)
  136. columns.value[0] = columns.value[0].filter((e) => e.isVirtual != true);
  137. });
  138. });
  139. }, 300);
  140. }
  141. /**
  142. * 根据ID移除指定项目
  143. * @param id 要移除的项目ID
  144. */
  145. function remove(id: string | number) {
  146. columns.value.forEach((column, columnIndex) => {
  147. // 过滤掉指定ID的项目
  148. columns.value[columnIndex] = column.filter((e) => e[props.nodeKey] != id);
  149. });
  150. }
  151. /**
  152. * 根据ID更新指定项目的数据
  153. * @param id 要更新的项目ID
  154. * @param data 新的数据对象
  155. */
  156. function update(id: string | number, data: UTSJSONObject) {
  157. columns.value.forEach((column) => {
  158. column.forEach((e) => {
  159. // 找到指定ID的项目并更新数据
  160. if (e[props.nodeKey] == id) {
  161. assign(e, data);
  162. }
  163. });
  164. });
  165. }
  166. /**
  167. * 清空瀑布流数据
  168. * 重新初始化列数组
  169. */
  170. function clear() {
  171. columns.value = [];
  172. // 根据列数创建空的列数组
  173. for (let i = 0; i < props.column; i++) {
  174. columns.value.push([]);
  175. }
  176. }
  177. // 组件挂载时的初始化逻辑
  178. onMounted(() => {
  179. // 监听列数变化,当列数改变时重新初始化
  180. watch(
  181. computed(() => props.column),
  182. () => {
  183. clear(); // 清空现有数据
  184. getHeight(); // 重新获取高度
  185. },
  186. {
  187. immediate: true // 立即执行一次
  188. }
  189. );
  190. });
  191. defineExpose({
  192. append,
  193. remove,
  194. update,
  195. clear
  196. });
  197. </script>
  198. <style lang="scss" scoped>
  199. .cl-waterfall {
  200. @apply flex flex-row w-full relative;
  201. &__column {
  202. flex: 1;
  203. }
  204. &__item {
  205. &.is-virtual {
  206. @apply absolute top-0 w-full;
  207. left: -100%;
  208. opacity: 0;
  209. }
  210. }
  211. }
  212. </style>