cl-list-view.uvue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. <template>
  2. <view class="cl-list-view" :class="[pt.className]">
  3. <!-- 滚动容器 -->
  4. <scroll-view
  5. class="cl-list-view__scroller"
  6. :class="[pt.scroller?.className]"
  7. :scroll-top="targetScrollTop"
  8. :scroll-into-view="scrollIntoView"
  9. :scroll-with-animation="scrollWithAnimation"
  10. :show-scrollbar="showScrollbar"
  11. :refresher-triggered="refreshTriggered"
  12. :refresher-enabled="refresherEnabled"
  13. :refresher-threshold="refresherThreshold"
  14. :refresher-background="refresherBackground"
  15. refresher-default-style="none"
  16. direction="vertical"
  17. @scrolltoupper="onScrollToUpper"
  18. @scrolltolower="onScrollToLower"
  19. @scroll="onScroll"
  20. @scrollend="onScrollEnd"
  21. @refresherpulling="onRefresherPulling"
  22. @refresherrefresh="onRefresherRefresh"
  23. @refresherrestore="onRefresherRestore"
  24. @refresherabort="onRefresherAbort"
  25. >
  26. <!-- 下拉刷新 -->
  27. <!-- #ifndef APP-HARMONY -->
  28. <view
  29. slot="refresher"
  30. class="cl-list-view__refresher"
  31. :class="[
  32. {
  33. 'is-pulling': refresherStatus === 'pulling',
  34. 'is-refreshing': refresherStatus === 'refreshing'
  35. },
  36. pt.refresher?.className
  37. ]"
  38. :style="{
  39. height: refresherThreshold + 'px'
  40. }"
  41. >
  42. <slot name="refresher" :status="refresherStatus" :text="refresherText">
  43. <cl-loading
  44. v-if="refresherStatus === 'refreshing'"
  45. :pt="{
  46. className: 'mr-2'
  47. }"
  48. ></cl-loading>
  49. <cl-text> {{ refresherText }} </cl-text>
  50. </slot>
  51. </view>
  52. <!-- #endif -->
  53. <!-- 列表 -->
  54. <view
  55. class="cl-list-view__virtual-list"
  56. :class="[pt.list?.className]"
  57. :style="listStyle"
  58. >
  59. <!-- 顶部占位 -->
  60. <view class="cl-list-view__spacer-top" :style="spacerTopStyle">
  61. <slot name="top"></slot>
  62. </view>
  63. <!-- 列表项 -->
  64. <view
  65. v-for="(item, index) in visibleItems"
  66. :key="item.key"
  67. class="cl-list-view__virtual-item"
  68. >
  69. <view
  70. class="cl-list-view__header"
  71. :class="[
  72. {
  73. 'is-dark': isDark
  74. }
  75. ]"
  76. :style="{
  77. height: headerHeight + 'px'
  78. }"
  79. v-if="item.type == 'header'"
  80. >
  81. <slot name="header" :index="item.data.index!">
  82. <cl-text> {{ item.data.label }} </cl-text>
  83. </slot>
  84. </view>
  85. <view
  86. v-else
  87. class="cl-list-view__item"
  88. :class="[
  89. {
  90. 'is-dark': isDark
  91. },
  92. pt.item?.className
  93. ]"
  94. :hover-class="pt.itemHover?.className"
  95. :style="{
  96. height: virtual ? itemHeight + 'px' : 'auto'
  97. }"
  98. @tap="onItemTap(item)"
  99. >
  100. <slot
  101. name="item"
  102. :item="item"
  103. :data="item.data"
  104. :value="item.data.value"
  105. :index="index"
  106. >
  107. <view class="cl-list-view__item-inner">
  108. <cl-text> {{ item.data.label }} </cl-text>
  109. </view>
  110. </slot>
  111. </view>
  112. </view>
  113. <!-- 底部占位 -->
  114. <view class="cl-list-view__spacer-bottom" :style="spacerBottomStyle">
  115. <slot name="bottom"></slot>
  116. </view>
  117. </view>
  118. <!-- 空状态 -->
  119. <cl-empty v-if="noData" :fixed="false"></cl-empty>
  120. </scroll-view>
  121. <!-- 右侧索引栏 -->
  122. <cl-index-bar
  123. v-if="hasIndex"
  124. v-model="activeIndex"
  125. :list="indexList"
  126. :pt="{
  127. className: parseClass([pt.indexBar?.className])
  128. }"
  129. @change="onIndexChange"
  130. >
  131. </cl-index-bar>
  132. <!-- 索引提示 -->
  133. <view
  134. class="cl-list-view__index"
  135. :class="[
  136. {
  137. 'is-dark': isDark
  138. }
  139. ]"
  140. :style="{ height: headerHeight + 'px' }"
  141. v-if="hasIndex"
  142. >
  143. <slot name="index" :index="indexList[activeIndex]">
  144. <cl-text> {{ indexList[activeIndex] }} </cl-text>
  145. </slot>
  146. </view>
  147. <!-- 回到顶部 -->
  148. <cl-back-top :top="scrollTop" v-if="showBackTop" @back-top="scrollToTop"></cl-back-top>
  149. </view>
  150. </template>
  151. <script setup lang="ts">
  152. import { computed, getCurrentInstance, nextTick, onMounted, ref, watch, type PropType } from "vue";
  153. import type {
  154. ClListViewItem,
  155. ClListViewGroup,
  156. ClListViewVirtualItem,
  157. PassThroughProps,
  158. ClListViewRefresherStatus
  159. } from "../../types";
  160. import { isApp, isDark, isEmpty, parseClass, parsePt, t } from "@/.cool";
  161. defineOptions({
  162. name: "cl-list-view"
  163. });
  164. defineSlots<{
  165. // 顶部插槽
  166. top(): any;
  167. // 分组头部插槽
  168. header(props: { index: string }): any;
  169. // 列表项插槽
  170. item(props: {
  171. data: ClListViewItem;
  172. item: ClListViewVirtualItem;
  173. value: any | null;
  174. index: number;
  175. }): any;
  176. // 底部插槽
  177. bottom(): any;
  178. // 索引插槽
  179. index(props: { index: string }): any;
  180. // 下拉刷新插槽
  181. refresher(props: { status: ClListViewRefresherStatus; text: string }): any;
  182. }>();
  183. const props = defineProps({
  184. // 透传样式配置
  185. pt: {
  186. type: Object,
  187. default: () => ({})
  188. },
  189. // 列表数据源
  190. data: {
  191. type: Array as PropType<ClListViewItem[]>,
  192. default: () => []
  193. },
  194. // 列表项高度
  195. itemHeight: {
  196. type: Number,
  197. default: 50
  198. },
  199. // 分组头部高度
  200. headerHeight: {
  201. type: Number,
  202. default: 32
  203. },
  204. // 列表顶部预留空间高度
  205. topHeight: {
  206. type: Number,
  207. default: 0
  208. },
  209. // 列表底部预留空间高度
  210. bottomHeight: {
  211. type: Number,
  212. default: 0
  213. },
  214. // 缓冲区大小,即可视区域外预渲染的项目数量
  215. bufferSize: {
  216. type: Number,
  217. default: isApp() ? 5 : 15
  218. },
  219. // 是否启用虚拟列表渲染,当数据量大时建议开启以提升性能
  220. virtual: {
  221. type: Boolean,
  222. default: true
  223. },
  224. // 滚动到指定位置
  225. scrollIntoView: {
  226. type: String,
  227. default: ""
  228. },
  229. // 是否启用滚动动画
  230. scrollWithAnimation: {
  231. type: Boolean,
  232. default: false
  233. },
  234. // 是否显示滚动条
  235. showScrollbar: {
  236. type: Boolean,
  237. default: false
  238. },
  239. // 是否启用下拉刷新
  240. refresherEnabled: {
  241. type: Boolean,
  242. default: false
  243. },
  244. // 下拉刷新触发距离,相当于下拉内容高度
  245. refresherThreshold: {
  246. type: Number,
  247. default: 50
  248. },
  249. // 下拉刷新区域背景色
  250. refresherBackground: {
  251. type: String,
  252. default: "transparent"
  253. },
  254. // 下拉刷新默认文案
  255. refresherDefaultText: {
  256. type: String,
  257. default: () => t("下拉刷新")
  258. },
  259. // 释放刷新文案
  260. refresherPullingText: {
  261. type: String,
  262. default: () => t("释放立即刷新")
  263. },
  264. // 正在刷新文案
  265. refresherRefreshingText: {
  266. type: String,
  267. default: () => t("加载中")
  268. },
  269. // 是否显示回到顶部按钮
  270. showBackTop: {
  271. type: Boolean,
  272. default: true
  273. }
  274. });
  275. const emit = defineEmits([
  276. "item-tap",
  277. "refresher-pulling",
  278. "refresher-refresh",
  279. "refresher-restore",
  280. "refresher-abort",
  281. "scrolltoupper",
  282. "scrolltolower",
  283. "scroll",
  284. "scrollend",
  285. "pull",
  286. "top",
  287. "bottom"
  288. ]);
  289. // 获取当前组件实例,用于后续DOM操作
  290. const { proxy } = getCurrentInstance()!;
  291. // 透传样式配置类型
  292. type PassThrough = {
  293. className?: string;
  294. item?: PassThroughProps;
  295. itemHover?: PassThroughProps;
  296. list?: PassThroughProps;
  297. indexBar?: PassThroughProps;
  298. scroller?: PassThroughProps;
  299. refresher?: PassThroughProps;
  300. };
  301. // 解析透传样式配置
  302. const pt = computed(() => parsePt<PassThrough>(props.pt));
  303. // 当前激活的索引位置,用于控制索引栏的高亮状态
  304. const activeIndex = ref(0);
  305. // 是否没有数据
  306. const noData = computed(() => {
  307. return isEmpty(props.data);
  308. });
  309. // 是否包含索引
  310. const hasIndex = computed(() => {
  311. return props.data.every((e) => e.index != null) && !noData.value;
  312. });
  313. // 计算属性:将原始数据按索引分组
  314. const data = computed<ClListViewGroup[]>(() => {
  315. // 初始化分组数组
  316. const group: ClListViewGroup[] = [];
  317. // 遍历原始数据,按index字段进行分组
  318. props.data.forEach((item) => {
  319. // 查找是否已存在相同index的分组
  320. const index = group.findIndex((group) => group.index == item.index);
  321. if (index != -1) {
  322. // 如果分组已存在,将当前项添加到该分组的列表中
  323. group[index].children.push(item);
  324. } else {
  325. // 如果分组不存在,创建新的分组
  326. group.push({
  327. index: item.index ?? "",
  328. children: [item]
  329. } as ClListViewGroup);
  330. }
  331. });
  332. return group;
  333. });
  334. // 计算属性:提取所有分组的索引列表,用于索引栏显示
  335. const indexList = computed<string[]>(() => {
  336. return data.value.map((item) => item.index);
  337. });
  338. // 计算属性:将分组数据扁平化为虚拟列表项数组
  339. const virtualItems = computed<ClListViewVirtualItem[]>(() => {
  340. // 初始化虚拟列表数组
  341. const items: ClListViewVirtualItem[] = [];
  342. // 初始化顶部位置,考虑预留空间
  343. let top = props.topHeight;
  344. // 初始化索引计数器
  345. let index = 0;
  346. // 遍历每个分组,生成虚拟列表项
  347. data.value.forEach((group, groupIndex) => {
  348. if (group.index != "") {
  349. // 添加分组头部项
  350. items.push({
  351. key: `header-${groupIndex}`,
  352. type: "header",
  353. index: index++,
  354. top,
  355. height: props.headerHeight,
  356. data: {
  357. label: group.index!,
  358. index: group.index
  359. }
  360. });
  361. // 更新top位置
  362. top += props.headerHeight;
  363. }
  364. // 添加分组内的所有列表项
  365. group.children.forEach((item, itemIndex) => {
  366. items.push({
  367. key: `item-${groupIndex}-${itemIndex}`,
  368. type: "item",
  369. index: index++,
  370. top,
  371. height: props.itemHeight,
  372. data: item
  373. });
  374. // 更新top位置
  375. top += props.itemHeight;
  376. });
  377. });
  378. return items;
  379. });
  380. // 计算属性:计算整个列表的总高度
  381. const listHeight = computed<number>(() => {
  382. return (
  383. // 所有项目高度之和
  384. virtualItems.value.reduce((total, item) => total + item.height, 0) +
  385. // 加上顶部预留空间高度
  386. props.topHeight +
  387. // 加上底部预留空间高度
  388. props.bottomHeight
  389. );
  390. });
  391. // 当前滚动位置
  392. const scrollTop = ref(0);
  393. // 目标滚动位置,用于控制滚动到指定位置
  394. const targetScrollTop = ref(0);
  395. // 滚动容器的高度
  396. const scrollerHeight = ref(0);
  397. // 计算属性:获取当前可见区域的列表项
  398. const visibleItems = computed<ClListViewVirtualItem[]>(() => {
  399. // 如果虚拟列表为空,返回空数组
  400. if (isEmpty(virtualItems.value)) {
  401. return [];
  402. }
  403. // 如果未启用虚拟列表,直接返回所有项目
  404. if (!props.virtual) {
  405. return virtualItems.value;
  406. }
  407. // 计算缓冲区高度
  408. const bufferHeight = props.bufferSize * props.itemHeight;
  409. // 计算可视区域的顶部位置(包含缓冲区)
  410. const viewportTop = scrollTop.value - bufferHeight;
  411. // 计算可视区域的底部位置(包含缓冲区)
  412. const viewportBottom = scrollTop.value + scrollerHeight.value + bufferHeight;
  413. // 初始化可见项目数组
  414. const visible: ClListViewVirtualItem[] = [];
  415. // 使用二分查找优化查找起始位置
  416. let startIndex = 0;
  417. let endIndex = virtualItems.value.length - 1;
  418. // 二分查找第一个可见项目的索引
  419. while (startIndex < endIndex) {
  420. const mid = Math.floor((startIndex + endIndex) / 2);
  421. const item = virtualItems.value[mid];
  422. if (item.top + item.height <= viewportTop) {
  423. startIndex = mid + 1;
  424. } else {
  425. endIndex = mid;
  426. }
  427. }
  428. // 从找到的起始位置开始,收集所有可见项目
  429. for (let i = startIndex; i < virtualItems.value.length; i++) {
  430. const item = virtualItems.value[i];
  431. // 如果项目完全超出视口下方,停止收集
  432. if (item.top >= viewportBottom) {
  433. break;
  434. }
  435. // 如果项目与视口有交集,添加到可见列表
  436. if (item.top + item.height > viewportTop) {
  437. visible.push(item);
  438. }
  439. }
  440. return visible;
  441. });
  442. // 计算属性:计算上方占位容器的高度
  443. const spacerTopHeight = computed<number>(() => {
  444. // 如果没有可见项目,返回0
  445. if (isEmpty(visibleItems.value)) {
  446. return 0;
  447. }
  448. // 返回第一个可见项目的顶部位置
  449. return visibleItems.value[0].top;
  450. });
  451. // 计算属性:计算下方占位容器的高度
  452. const spacerBottomHeight = computed<number>(() => {
  453. // 如果没有可见项目,返回0
  454. if (isEmpty(visibleItems.value)) {
  455. return 0;
  456. }
  457. // 获取最后一个可见项目
  458. const lastItem = visibleItems.value[visibleItems.value.length - 1];
  459. // 计算下方占位高度
  460. return listHeight.value - (lastItem.top + lastItem.height);
  461. });
  462. // 列表样式
  463. const listStyle = computed(() => {
  464. return {
  465. height: props.virtual ? `${listHeight.value}px` : "auto"
  466. };
  467. });
  468. // 上方占位容器样式
  469. const spacerTopStyle = computed(() => {
  470. return {
  471. height: props.virtual ? `${spacerTopHeight.value}px` : "auto"
  472. };
  473. });
  474. // 下方占位容器样式
  475. const spacerBottomStyle = computed(() => {
  476. return {
  477. height: props.virtual ? `${spacerBottomHeight.value}px` : "auto"
  478. };
  479. });
  480. // 存储每个分组头部距离顶部的位置数组
  481. const tops = ref<number[]>([]);
  482. // 计算并更新所有分组头部的位置
  483. function getTops() {
  484. // 初始化一个空数组
  485. const arr = [] as number[];
  486. // 初始化顶部位置
  487. let top = 0;
  488. // 计算每个分组的顶部位置
  489. data.value.forEach((group) => {
  490. // 将当前分组头部的位置添加到数组中
  491. arr.push(top);
  492. // 累加当前分组的总高度(头部高度+所有项目高度)
  493. top += props.headerHeight + group.children.length * props.itemHeight;
  494. });
  495. tops.value = arr;
  496. }
  497. // 下拉刷新触发标志
  498. const refreshTriggered = ref(false);
  499. // 下拉刷新相关状态
  500. const refresherStatus = ref<"default" | "pulling" | "refreshing">("default");
  501. // 下拉刷新文案
  502. const refresherText = computed(() => {
  503. switch (refresherStatus.value) {
  504. case "pulling":
  505. return props.refresherPullingText;
  506. case "refreshing":
  507. return props.refresherRefreshingText;
  508. default:
  509. return props.refresherDefaultText;
  510. }
  511. });
  512. // 停止下拉刷新
  513. function stopRefresh() {
  514. refresherStatus.value = "default";
  515. refreshTriggered.value = false;
  516. }
  517. // 滚动到顶部事件处理函数
  518. function onScrollToUpper(e: UniScrollToUpperEvent) {
  519. emit("scrolltoupper", e);
  520. emit("top");
  521. }
  522. // 滚动到底部事件处理函数
  523. function onScrollToLower(e: UniScrollToLowerEvent) {
  524. emit("scrolltolower", e);
  525. emit("bottom");
  526. }
  527. // 滚动锁定标志,用于防止滚动时触发不必要的计算
  528. let scrollLock = false;
  529. // 滚动事件处理函数
  530. function onScroll(e: UniScrollEvent) {
  531. // 更新当前滚动位置
  532. scrollTop.value = Math.floor(e.detail.scrollTop);
  533. // 如果滚动被锁定,直接返回
  534. if (scrollLock) return;
  535. // 根据滚动位置自动更新激活的索引
  536. tops.value.forEach((top, index) => {
  537. if (scrollTop.value >= top) {
  538. activeIndex.value = index;
  539. }
  540. });
  541. emit("scroll", e);
  542. }
  543. // 滚动结束事件处理函数
  544. function onScrollEnd(e: UniScrollEvent) {
  545. emit("scrollend", e);
  546. }
  547. // 行点击事件处理函数
  548. function onItemTap(item: ClListViewVirtualItem) {
  549. emit("item-tap", item.data);
  550. }
  551. // 索引栏点击事件处理函数
  552. function onIndexChange(index: number) {
  553. // 锁定滚动,防止触发不必要的计算
  554. scrollLock = true;
  555. // 设置目标滚动位置为对应分组头部的位置
  556. targetScrollTop.value = tops.value[index];
  557. // 300ms后解除滚动锁定
  558. setTimeout(() => {
  559. scrollLock = false;
  560. }, 300);
  561. }
  562. // 下拉刷新事件处理函数
  563. function onRefresherPulling(e: UniRefresherEvent) {
  564. if (e.detail.dy > props.refresherThreshold) {
  565. refresherStatus.value = "pulling";
  566. }
  567. emit("refresher-pulling", e);
  568. }
  569. // 下拉刷新事件处理函数
  570. function onRefresherRefresh(e: UniRefresherEvent) {
  571. refresherStatus.value = "refreshing";
  572. refreshTriggered.value = true;
  573. emit("refresher-refresh", e);
  574. emit("pull", e);
  575. }
  576. // 恢复下拉刷新
  577. function onRefresherRestore(e: UniRefresherEvent) {
  578. refresherStatus.value = "default";
  579. emit("refresher-restore", e);
  580. }
  581. // 停止下拉刷新
  582. function onRefresherAbort(e: UniRefresherEvent) {
  583. refresherStatus.value = "default";
  584. emit("refresher-abort", e);
  585. }
  586. // 滚动到顶部
  587. function scrollToTop() {
  588. targetScrollTop.value = 0.01;
  589. nextTick(() => {
  590. targetScrollTop.value = 0;
  591. });
  592. }
  593. // 获取滚动容器的高度
  594. function getScrollerHeight() {
  595. setTimeout(() => {
  596. uni.createSelectorQuery()
  597. .in(proxy)
  598. .select(".cl-list-view__scroller")
  599. .boundingClientRect()
  600. .exec((res) => {
  601. if (isEmpty(res)) {
  602. return;
  603. }
  604. // 设置容器高度
  605. scrollerHeight.value = (res[0] as NodeInfo).height ?? 0;
  606. });
  607. }, 100);
  608. }
  609. // 组件挂载后的初始化逻辑
  610. onMounted(() => {
  611. // 获取容器高度
  612. getScrollerHeight();
  613. // 监听数据变化,重新计算位置信息
  614. watch(
  615. computed(() => props.data),
  616. () => {
  617. getTops();
  618. },
  619. {
  620. // 立即执行一次
  621. immediate: true
  622. }
  623. );
  624. });
  625. defineExpose({
  626. data,
  627. stopRefresh
  628. });
  629. </script>
  630. <style lang="scss" scoped>
  631. .cl-list-view {
  632. @apply h-full w-full relative;
  633. &__scroller {
  634. @apply h-full w-full;
  635. }
  636. &__virtual-list {
  637. @apply relative w-full;
  638. }
  639. &__spacer-top,
  640. &__spacer-bottom {
  641. @apply w-full;
  642. }
  643. &__index {
  644. @apply flex flex-row items-center bg-white;
  645. @apply absolute top-0 left-0 w-full px-[10px] z-20;
  646. &.is-dark {
  647. @apply bg-surface-600 border-none;
  648. }
  649. }
  650. &__virtual-item {
  651. @apply w-full;
  652. }
  653. &__header {
  654. @apply flex flex-row items-center relative px-[10px] z-10;
  655. }
  656. &__item {
  657. &-inner {
  658. @apply flex flex-row items-center px-[10px] h-full;
  659. }
  660. }
  661. &__refresher {
  662. @apply flex flex-row items-center justify-center w-full h-full;
  663. }
  664. }
  665. </style>