cl-list-view.uvue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <template>
  2. <view class="cl-list-view">
  3. <cl-index-bar
  4. v-if="hasIndex"
  5. v-model="activeIndex"
  6. :list="indexList"
  7. :pt="{
  8. className: parseClass([pt.indexBar?.className])
  9. }"
  10. @change="onIndexChange"
  11. >
  12. </cl-index-bar>
  13. <scroll-view
  14. class="cl-list-view__scroller"
  15. :scroll-top="targetScrollTop"
  16. :show-scrollbar="false"
  17. direction="vertical"
  18. @scroll="onScroll"
  19. >
  20. <view class="cl-list-view__virtual-list" :style="{ height: listHeight + 'px' }">
  21. <view class="cl-list-view__spacer-top" :style="{ height: spacerTopHeight + 'px' }">
  22. <slot name="top"></slot>
  23. </view>
  24. <view
  25. v-for="item in visibleItems"
  26. :key="item.key"
  27. class="cl-list-view__virtual-item"
  28. >
  29. <view
  30. class="cl-list-view__header"
  31. :class="[
  32. {
  33. 'is-dark': isDark
  34. }
  35. ]"
  36. :style="{
  37. height: headerHeight + 'px'
  38. }"
  39. v-if="item.type == 'header'"
  40. >
  41. <slot name="header" :index="item.data.index!">
  42. <cl-text> {{ item.data.label }} </cl-text>
  43. </slot>
  44. </view>
  45. <view
  46. v-else
  47. class="cl-list-view__item"
  48. :class="[
  49. {
  50. 'is-dark': isDark
  51. },
  52. pt.item?.className
  53. ]"
  54. :hover-class="parseClass([[isDark, '!bg-surface-800', '!bg-surface-50']])"
  55. :hover-stay-time="50"
  56. :style="{
  57. height: itemHeight + 'px'
  58. }"
  59. @tap="onItemTap(item)"
  60. >
  61. <slot name="item" :data="item.data" :item="item">
  62. <view class="cl-list-view__item-inner">
  63. <cl-text> {{ item.data.label }} </cl-text>
  64. </view>
  65. </slot>
  66. </view>
  67. </view>
  68. <view
  69. class="cl-list-view__spacer-bottom"
  70. :style="{ height: spacerBottomHeight + 'px' }"
  71. >
  72. <slot name="bottom"></slot>
  73. </view>
  74. </view>
  75. <cl-empty v-if="noData" :fixed="false"></cl-empty>
  76. </scroll-view>
  77. <view
  78. class="cl-list-view__index"
  79. :class="[
  80. {
  81. 'is-dark': isDark
  82. }
  83. ]"
  84. :style="{ height: headerHeight + 'px' }"
  85. v-if="hasIndex"
  86. >
  87. <slot name="index" :index="indexList[activeIndex]">
  88. <cl-text> {{ indexList[activeIndex] }} </cl-text>
  89. </slot>
  90. </view>
  91. </view>
  92. </template>
  93. <script setup lang="ts">
  94. import { computed, getCurrentInstance, onMounted, ref, watch, type PropType } from "vue";
  95. import type { ClListViewItem, PassThroughProps } from "../../types";
  96. import { isApp, isDark, isEmpty, parseClass, parsePt } from "@/cool";
  97. // 定义虚拟列表项
  98. type VirtualItem = {
  99. // 每一项的唯一标识符,用于v-for的key
  100. key: string;
  101. // 项目类型:header表示分组头部,item表示列表项
  102. type: "header" | "item";
  103. // 在整个列表中的索引号
  104. index: number;
  105. // 该项距离列表顶部的像素距离
  106. top: number;
  107. // 该项的高度,header和item可以不同
  108. height: number;
  109. // 该项的具体数据
  110. data: ClListViewItem;
  111. };
  112. type Group = {
  113. index: string;
  114. children: ClListViewItem[];
  115. };
  116. defineOptions({
  117. name: "cl-list-view"
  118. });
  119. defineSlots<{
  120. // 顶部插槽
  121. top(): any;
  122. // 分组头部插槽
  123. header(props: { index: string }): any;
  124. // 列表项插槽
  125. item(props: { data: ClListViewItem; item: VirtualItem }): any;
  126. // 底部插槽
  127. bottom(): any;
  128. // 索引插槽
  129. index(props: { index: string }): any;
  130. }>();
  131. const props = defineProps({
  132. // 透传样式配置
  133. pt: {
  134. type: Object,
  135. default: () => ({})
  136. },
  137. // 列表数据源
  138. data: {
  139. type: Array as PropType<ClListViewItem[]>,
  140. default: () => []
  141. },
  142. // 列表项高度
  143. itemHeight: {
  144. type: Number,
  145. default: 50
  146. },
  147. // 分组头部高度
  148. headerHeight: {
  149. type: Number,
  150. default: 32
  151. },
  152. // 列表顶部预留空间高度
  153. topHeight: {
  154. type: Number,
  155. default: 0
  156. },
  157. // 列表底部预留空间高度
  158. bottomHeight: {
  159. type: Number,
  160. default: 0
  161. },
  162. // 缓冲区大小,即可视区域外预渲染的项目数量
  163. bufferSize: {
  164. type: Number,
  165. default: isApp() ? 5 : 15
  166. },
  167. // 是否启用虚拟列表渲染,当数据量大时建议开启以提升性能
  168. virtual: {
  169. type: Boolean,
  170. default: true
  171. }
  172. });
  173. const emit = defineEmits(["item-tap"]);
  174. // 获取当前组件实例,用于后续DOM操作
  175. const { proxy } = getCurrentInstance()!;
  176. type PassThrough = {
  177. className?: string;
  178. item?: PassThroughProps;
  179. indexBar?: PassThroughProps;
  180. };
  181. // 解析透传样式配置
  182. const pt = computed(() => parsePt<PassThrough>(props.pt));
  183. // 当前激活的索引位置,用于控制索引栏的高亮状态
  184. const activeIndex = ref(0);
  185. // 是否没有数据
  186. const noData = computed(() => {
  187. return isEmpty(props.data);
  188. });
  189. // 是否包含索引
  190. const hasIndex = computed(() => {
  191. return props.data.every((e) => e.index != null) && !noData.value;
  192. });
  193. // 计算属性:将原始数据按索引分组
  194. const data = computed<Group[]>(() => {
  195. // 初始化分组数组
  196. const group: Group[] = [];
  197. // 遍历原始数据,按index字段进行分组
  198. props.data.forEach((item) => {
  199. // 查找是否已存在相同index的分组
  200. const index = group.findIndex((group) => group.index == item.index);
  201. if (index != -1) {
  202. // 如果分组已存在,将当前项添加到该分组的列表中
  203. group[index].children.push(item);
  204. } else {
  205. // 如果分组不存在,创建新的分组
  206. group.push({
  207. index: item.index ?? "",
  208. children: [item]
  209. } as Group);
  210. }
  211. });
  212. return group;
  213. });
  214. // 计算属性:提取所有分组的索引列表,用于索引栏显示
  215. const indexList = computed<string[]>(() => {
  216. return data.value.map((item) => item.index);
  217. });
  218. // 计算属性:将分组数据扁平化为虚拟列表项数组
  219. const virtualItems = computed<VirtualItem[]>(() => {
  220. // 初始化虚拟列表数组
  221. const items: VirtualItem[] = [];
  222. // 初始化顶部位置,考虑预留空间
  223. let top = props.topHeight;
  224. // 初始化索引计数器
  225. let index = 0;
  226. // 遍历每个分组,生成虚拟列表项
  227. data.value.forEach((group, groupIndex) => {
  228. if (group.index != "") {
  229. // 添加分组头部项
  230. items.push({
  231. key: `header-${groupIndex}`,
  232. type: "header",
  233. index: index++,
  234. top,
  235. height: props.headerHeight,
  236. data: {
  237. label: group.index!,
  238. index: group.index
  239. }
  240. });
  241. // 更新top位置
  242. top += props.headerHeight;
  243. }
  244. // 添加分组内的所有列表项
  245. group.children.forEach((item, itemIndex) => {
  246. items.push({
  247. key: `item-${groupIndex}-${itemIndex}`,
  248. type: "item",
  249. index: index++,
  250. top,
  251. height: props.itemHeight,
  252. data: item
  253. });
  254. // 更新top位置
  255. top += props.itemHeight;
  256. });
  257. });
  258. return items;
  259. });
  260. // 计算属性:计算整个列表的总高度
  261. const listHeight = computed<number>(() => {
  262. return (
  263. // 所有项目高度之和
  264. virtualItems.value.reduce((total, item) => total + item.height, 0) +
  265. // 加上顶部预留空间高度
  266. props.topHeight +
  267. // 加上底部预留空间高度
  268. props.bottomHeight
  269. );
  270. });
  271. // 当前滚动位置
  272. const scrollTop = ref(0);
  273. // 目标滚动位置,用于控制滚动到指定位置
  274. const targetScrollTop = ref(0);
  275. // 滚动容器的高度
  276. const scrollerHeight = ref(0);
  277. // 计算属性:获取当前可见区域的列表项
  278. const visibleItems = computed<VirtualItem[]>(() => {
  279. // 如果虚拟列表为空,返回空数组
  280. if (isEmpty(virtualItems.value)) {
  281. return [];
  282. }
  283. // 如果未启用虚拟列表,直接返回所有项目
  284. if (!props.virtual) {
  285. return virtualItems.value;
  286. }
  287. // 计算缓冲区高度
  288. const bufferHeight = props.bufferSize * props.itemHeight;
  289. // 计算可视区域的顶部位置(包含缓冲区)
  290. const viewportTop = scrollTop.value - bufferHeight;
  291. // 计算可视区域的底部位置(包含缓冲区)
  292. const viewportBottom = scrollTop.value + scrollerHeight.value + bufferHeight;
  293. // 初始化可见项目数组
  294. const visible: VirtualItem[] = [];
  295. // 使用二分查找优化查找起始位置
  296. let startIndex = 0;
  297. let endIndex = virtualItems.value.length - 1;
  298. // 二分查找第一个可见项目的索引
  299. while (startIndex < endIndex) {
  300. const mid = Math.floor((startIndex + endIndex) / 2);
  301. const item = virtualItems.value[mid];
  302. if (item.top + item.height <= viewportTop) {
  303. startIndex = mid + 1;
  304. } else {
  305. endIndex = mid;
  306. }
  307. }
  308. // 从找到的起始位置开始,收集所有可见项目
  309. for (let i = startIndex; i < virtualItems.value.length; i++) {
  310. const item = virtualItems.value[i];
  311. // 如果项目完全超出视口下方,停止收集
  312. if (item.top >= viewportBottom) {
  313. break;
  314. }
  315. // 如果项目与视口有交集,添加到可见列表
  316. if (item.top + item.height > viewportTop) {
  317. visible.push(item);
  318. }
  319. }
  320. return visible;
  321. });
  322. // 计算属性:计算上方占位容器的高度
  323. const spacerTopHeight = computed<number>(() => {
  324. // 如果没有可见项目,返回0
  325. if (isEmpty(visibleItems.value)) {
  326. return 0;
  327. }
  328. // 如果未启用虚拟列表,返回0
  329. if (!props.virtual) {
  330. return 0;
  331. }
  332. // 返回第一个可见项目的顶部位置
  333. return visibleItems.value[0].top;
  334. });
  335. // 计算属性:计算下方占位容器的高度
  336. const spacerBottomHeight = computed<number>(() => {
  337. // 如果没有可见项目,返回0
  338. if (isEmpty(visibleItems.value)) {
  339. return 0;
  340. }
  341. // 如果未启用虚拟列表,返回0
  342. if (!props.virtual) {
  343. return 0;
  344. }
  345. // 获取最后一个可见项目
  346. const lastItem = visibleItems.value[visibleItems.value.length - 1];
  347. // 计算下方占位高度
  348. return listHeight.value - (lastItem.top + lastItem.height);
  349. });
  350. // 存储每个分组头部距离顶部的位置数组
  351. const tops = ref<number[]>([]);
  352. // 计算并更新所有分组头部的位置
  353. function getTops() {
  354. // 初始化一个空数组
  355. const arr = [] as number[];
  356. // 初始化顶部位置
  357. let top = 0;
  358. // 计算每个分组的顶部位置
  359. data.value.forEach((group) => {
  360. // 将当前分组头部的位置添加到数组中
  361. arr.push(top);
  362. // 累加当前分组的总高度(头部高度+所有项目高度)
  363. top += props.headerHeight + group.children.length * props.itemHeight;
  364. });
  365. tops.value = arr;
  366. }
  367. // 滚动锁定标志,用于防止滚动时触发不必要的计算
  368. let scrollLock = false;
  369. // 滚动事件处理函数
  370. function onScroll(e: UniScrollEvent) {
  371. // 更新当前滚动位置
  372. scrollTop.value = Math.floor(e.detail.scrollTop);
  373. // 如果滚动被锁定,直接返回
  374. if (scrollLock) return;
  375. // 根据滚动位置自动更新激活的索引
  376. tops.value.forEach((top, index) => {
  377. if (scrollTop.value >= top) {
  378. activeIndex.value = index;
  379. }
  380. });
  381. }
  382. // 行点击事件处理函数
  383. function onItemTap(item: VirtualItem) {
  384. emit("item-tap", item.data);
  385. }
  386. // 索引栏点击事件处理函数
  387. function onIndexChange(index: number) {
  388. // 锁定滚动,防止触发不必要的计算
  389. scrollLock = true;
  390. // 设置目标滚动位置为对应分组头部的位置
  391. targetScrollTop.value = tops.value[index];
  392. // 300ms后解除滚动锁定
  393. setTimeout(() => {
  394. scrollLock = false;
  395. }, 300);
  396. }
  397. // 获取滚动容器的高度
  398. function getScrollerHeight() {
  399. setTimeout(() => {
  400. uni.createSelectorQuery()
  401. .in(proxy)
  402. .select(".cl-list-view__scroller")
  403. .boundingClientRect()
  404. .exec((res) => {
  405. if (isEmpty(res)) {
  406. return;
  407. }
  408. // 设置容器高度
  409. scrollerHeight.value = (res[0] as NodeInfo).height ?? 0;
  410. });
  411. }, 100);
  412. }
  413. // 组件挂载后的初始化逻辑
  414. onMounted(() => {
  415. // 获取容器高度
  416. getScrollerHeight();
  417. // 监听数据变化,重新计算位置信息
  418. watch(
  419. computed(() => props.data),
  420. () => {
  421. getTops();
  422. },
  423. {
  424. // 立即执行一次
  425. immediate: true
  426. }
  427. );
  428. });
  429. </script>
  430. <style lang="scss" scoped>
  431. .cl-list-view {
  432. @apply h-full w-full relative;
  433. &__scroller {
  434. @apply h-full w-full;
  435. }
  436. &__virtual-list {
  437. @apply relative w-full;
  438. }
  439. &__spacer-top,
  440. &__spacer-bottom {
  441. @apply w-full;
  442. }
  443. &__index {
  444. @apply flex flex-row items-center bg-white;
  445. @apply absolute top-0 left-0 w-full;
  446. top: 0px;
  447. padding: 0 20rpx;
  448. z-index: 11;
  449. &.is-dark {
  450. @apply bg-surface-600 border-none;
  451. }
  452. }
  453. &__virtual-item {
  454. @apply w-full;
  455. }
  456. &__header {
  457. @apply flex flex-row items-center;
  458. padding: 0 20rpx;
  459. position: relative;
  460. z-index: 10;
  461. }
  462. &__item {
  463. &-inner {
  464. @apply flex flex-row items-center px-[20rpx] h-full;
  465. }
  466. }
  467. }
  468. </style>