cl-waterfall.uvue 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 } 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<number> 返回Promise对象
  80. */
  81. async function getHeight(): Promise<number> {
  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. // 提取每列的高度信息,如果获取失败则默认为0
  92. heights.value = (rect[0] as NodeInfo[]).map((e) => e.height ?? 0);
  93. resolve(1);
  94. });
  95. });
  96. }
  97. /**
  98. * 向瀑布流添加新数据
  99. * 使用虚拟定位技术计算每个项目的高度,然后分配到最短的列
  100. * @param data 要添加的数据数组
  101. */
  102. async function append(data: UTSJSONObject[]) {
  103. // 首先获取当前各列高度
  104. await getHeight();
  105. // 将新数据作为虚拟项目添加到第一列,用于计算高度
  106. columns.value[0].push(
  107. ...data.map((e) => {
  108. return {
  109. ...e,
  110. isVirtual: true // 标记为虚拟项目,会在CSS中隐藏
  111. } as UTSJSONObject;
  112. })
  113. );
  114. // 等待DOM更新
  115. await nextTick();
  116. // 延迟300ms后计算虚拟项目的高度并重新分配
  117. setTimeout(() => {
  118. uni.createSelectorQuery()
  119. .in(proxy)
  120. .selectAll(".is-virtual")
  121. .boundingClientRect()
  122. .exec((rect) => {
  123. // 遍历每个虚拟项目
  124. (rect[0] as NodeInfo[]).forEach((e, i) => {
  125. // 找到当前高度最小的列
  126. const min = Math.min(...heights.value);
  127. const index = heights.value.indexOf(min);
  128. // 将实际数据添加到最短列
  129. columns.value[index].push(data[i]);
  130. // 更新该列的高度
  131. heights.value[index] += e.height ?? 0;
  132. // 清除第一列中的虚拟项目(临时用于计算高度的项目)
  133. columns.value[0] = columns.value[0].filter((e) => e.isVirtual != true);
  134. });
  135. });
  136. }, 300);
  137. }
  138. /**
  139. * 根据ID移除指定项目
  140. * @param id 要移除的项目ID
  141. */
  142. function remove(id: string | number) {
  143. columns.value.forEach((column, columnIndex) => {
  144. // 过滤掉指定ID的项目
  145. columns.value[columnIndex] = column.filter((e) => e[props.nodeKey] != id);
  146. });
  147. }
  148. /**
  149. * 根据ID更新指定项目的数据
  150. * @param id 要更新的项目ID
  151. * @param data 新的数据对象
  152. */
  153. function update(id: string | number, data: UTSJSONObject) {
  154. columns.value.forEach((column) => {
  155. column.forEach((e) => {
  156. // 找到指定ID的项目并更新数据
  157. if (e[props.nodeKey] == id) {
  158. assign(e, data);
  159. }
  160. });
  161. });
  162. }
  163. /**
  164. * 清空瀑布流数据
  165. * 重新初始化列数组
  166. */
  167. function clear() {
  168. columns.value = [];
  169. // 根据列数创建空的列数组
  170. for (let i = 0; i < props.column; i++) {
  171. columns.value.push([]);
  172. }
  173. }
  174. // 组件挂载时的初始化逻辑
  175. onMounted(() => {
  176. // 监听列数变化,当列数改变时重新初始化
  177. watch(
  178. computed(() => props.column),
  179. () => {
  180. clear(); // 清空现有数据
  181. getHeight(); // 重新获取高度
  182. },
  183. {
  184. immediate: true // 立即执行一次
  185. }
  186. );
  187. });
  188. defineExpose({
  189. append,
  190. remove,
  191. update,
  192. clear
  193. });
  194. </script>
  195. <style lang="scss" scoped>
  196. .cl-waterfall {
  197. @apply flex flex-row w-full relative;
  198. &__column {
  199. flex: 1;
  200. }
  201. &__item {
  202. &.is-virtual {
  203. @apply absolute top-0 w-full;
  204. left: -100%;
  205. opacity: 0;
  206. }
  207. }
  208. }
  209. </style>