index.vue 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
<!--
  @description 通用加载更多列表组件
  @features
  - 支持自定义头部(通过slot)
  - 支持下拉刷新
  - 支持触底加载更多(带防抖)
  - 支持多种列表项渲染(通过slot)
  - 内置空状态和加载提示
  - 内置列表项动画效果

  @example
  <LoadMoreList
    :list="products"
    :page="page"
    :page-size="pageSize"
    :has-more="hasMore"
    :loading="loading"
    :loading-more="loadingMore"
    key-field="id"
    @load-more="handleLoadMore"
    @refresh="handleRefresh"
  >
    <template #header>
      <NavHeader title="产品中心" />
    </template>
    <template #item="{ item }">
      <ProductCard :product="item" />
    </template>
  </LoadMoreList>
-->
<template>
  <view class="load-more-list" :class="{ 'has-header': showHeader }">
    <!-- 可选固定头部 -->
    <view v-if="showHeader" class="load-more-header" ref="headerRef">
      <slot name="header"></slot>
    </view>

    <!-- 可滚动的列表容器 -->
    <scroll-view
      v-if="enableScrollLoad && list.length > 0"
      class="load-more-content scrollable"
      :class="{ 'no-padding': noPadding }"
      :style="{ height: scrollHeight }"
      :scroll-y="true"
      lower-threshold="100"
      @scrolltolower="handleScrollToLower"
    >
      <!-- 列表内容 -->
      <view class="list-container">
        <view
          v-for="(item, index) in displayList"
          :key="item[keyField] || index"
          class="list-item"
          :style="getAnimationDelay(index)"
        >
          <!-- 使用slot渲染每个列表项 -->
          <slot name="item" :item="item" :index="index"></slot>
        </view>

        <!-- 加载更多提示 -->
        <view v-if="list.length > 0" class="load-more-container">
          <view v-if="loadingMore" class="load-more-loading">
            <slot name="loading-more">
              <view class="loading-spinner-small"></view>
              <text class="ml-[16rpx] text-[#9CA3AF] text-[24rpx]">加载中...</text>
            </slot>
          </view>
          <view v-else-if="!hasMore" class="load-more-finished">
            <slot name="no-more">
              <text class="text-[#9CA3AF] text-[24rpx]">没有更多了</text>
            </slot>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 不可滚动的列表容器 -->
    <view
      v-else
      class="load-more-content"
      :class="{ 'no-padding': noPadding }"
    >
      <!-- 首次加载状态 -->
      <view v-if="loading && list.length === 0" class="flex justify-center items-center py-[100rpx]">
        <slot name="loading">
          <view class="loading-spinner"></view>
          <text class="ml-[16rpx] text-[#9CA3AF] text-[28rpx]">加载中...</text>
        </slot>
      </view>

      <!-- 列表内容 -->
      <view v-else class="list-container">
        <view
          v-for="(item, index) in displayList"
          :key="item[keyField] || index"
          class="list-item"
          :style="getAnimationDelay(index)"
        >
          <!-- 使用slot渲染每个列表项 -->
          <slot name="item" :item="item" :index="index"></slot>
        </view>

        <!-- 空状态 -->
        <view v-if="list.length === 0 && !loading && !loadingMore">
          <slot name="empty">
            <nut-empty description="暂无数据" image="empty" />
          </slot>
        </view>

        <!-- 加载更多提示 -->
        <view v-if="list.length > 0" class="load-more-container">
          <view v-if="loadingMore" class="load-more-loading">
            <slot name="loading-more">
              <view class="loading-spinner-small"></view>
              <text class="ml-[16rpx] text-[#9CA3AF] text-[24rpx]">加载中...</text>
            </slot>
          </view>
          <view v-else-if="!hasMore" class="load-more-finished">
            <slot name="no-more">
              <text class="text-[#9CA3AF] text-[24rpx]">没有更多了</text>
            </slot>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, onMounted, watch, nextTick as vueNextTick } from 'vue'
import Taro from '@tarojs/taro'
import { usePullDownRefresh, stopPullDownRefresh, useDidShow } from '@tarojs/taro'

/**
 * 通用加载更多列表组件
 *
 * @description 封装分页加载逻辑,支持自定义头部、列表项、空状态。
 *           页面只需提供数据源和事件处理,组件内部处理触底加载、状态显示等。
 *
 * @component LoadMoreList
 *
 * @example
 * <!-- 简单列表(无头部) -->
 * <LoadMoreList
 *   :list="products"
 *   :page="page"
 *   :page-size="10"
 *   :has-more="hasMore"
 *   :loading="loading"
 *   :loading-more="loadingMore"
 *   key-field="id"
 *   @load-more="handleLoadMore"
 * >
 *   <template #item="{ item }">
 *     <ProductCard :product="item" />
 *   </template>
 * </LoadMoreList>
 *
 * @example
 * <!-- 带头部和搜索的列表 -->
 * <LoadMoreList
 *   :list="products"
 *   :page="page"
 *   :page-size="10"
 *   :has-more="hasMore"
 *   :loading="loading"
 *   :loading-more="loadingMore"
 *   :enable-pull-down-refresh="true"
 *   @load-more="handleLoadMore"
 *   @refresh="handleRefresh"
 * >
 *   <template #header>
 *     <NavHeader title="产品中心" />
 *     <SearchBar v-model="searchValue" @search="onSearch" />
 *   </template>
 *   <template #item="{ item }">
 *     <ProductCard :product="item" />
 *   </template>
 *   <template #empty>
 *     <nut-empty description="暂无相关产品" image="empty" />
 *   </template>
 * </LoadMoreList>
 */
const props = defineProps({
  /**
   * 列表数据源
   * @type {Array<any>}
   * @description 需要渲染的列表数据数组
   */
  list: {
    type: Array,
    default: () => []
  },

  /**
   * 当前页码
   * @type {number}
   * @description 当前页码(从0或1开始,根据API要求)
   */
  page: {
    type: Number,
    required: true
  },

  /**
   * 每页数量
   * @type {number}
   * @default 10
   * @description 每页显示的数据条数
   */
  pageSize: {
    type: Number,
    default: 10
  },

  /**
   * 是否还有更多数据
   * @type {boolean}
   * @default true
   * @description 用于控制是否显示"没有更多了"提示
   */
  hasMore: {
    type: Boolean,
    default: true
  },

  /**
   * 首次加载状态
   * @type {boolean}
   * @default false
   * @description 首次加载时显示loading,隐藏列表
   */
  loading: {
    type: Boolean,
    default: false
  },

  /**
   * 加载更多状态
   * @type {boolean}
   * @default false
   * @description 加载更多时在列表底部显示loading
   */
  loadingMore: {
    type: Boolean,
    default: false
  },

  /**
   * 唯一标识字段名
   * @type {string}
   * @default 'id'
   * @description 用于v-for的key字段名,确保列表更新正确
   */
  keyField: {
    type: String,
    default: 'id'
  },

  /**
   * 是否显示固定头部
   * @type {boolean}
   * @default true
   * @description 是否在顶部显示固定的头部区域
   */
  showHeader: {
    type: Boolean,
    default: true
  },

  /**
   * 是否启用下拉刷新
   * @type {boolean}
   * @default false
   * @description 启用后,用户下拉会触发refresh事件
   */
  enablePullDownRefresh: {
    type: Boolean,
    default: false
  },

  /**
   * 列表容器是否不需要padding
   * @type {boolean}
   * @default false
   * @description 设为true时,列表容器不添加默认的左右padding
   */
  noPadding: {
    type: Boolean,
    default: false
  },

  /**
   * 是否启用滚动加载更多
   * @type {boolean}
   * @default true
   * @description 设为false时,禁用触底加载更多功能(适用于数据较少的情况)
   */
  enableScrollLoad: {
    type: Boolean,
    default: true
  },

  /**
   * 页面是否有底部导航(TabBar 等)
   * @type {boolean}
   * @default false
   * @description 如果页面有底部导航(如 TabBar),设为 true 会自动预留底部空间
   */
  hasFooter: {
    type: Boolean,
    default: false
  },

  /**
   * 额外底部空间(rpx)
   * @type {number}
   * @default 0
   * @description 额外预留的底部空间(单位:rpx),用于固定按钮等非标准底部元素
   */
  extraBottomSpace: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits({
  /**
   * 加载更多事件
   * @event {number} page - 下一页页码
   * @description 当用户滚动到底部时触发,页码自动+1
   */
  'load-more': (page) => typeof page === 'number',

  /**
   * 下拉刷新事件
   * @description 当用户下拉刷新时触发,仅当enablePullDownRefresh为true时有效
   */
  'refresh': null
})

/**
 * 显示列表(用于渲染)
 * @description 计算属性,返回非空的列表数组
 */
const displayList = computed(() => props.list || [])

/**
 * 动态测量的头部高度(px)
 * @description 使用 Taro.createSelectorQuery() 在运行时测量实际头部高度
 */
const headerHeight = ref(0)

/**
 * 动态测量的底部导航高度(px)
 * @description 如果页面有 TabBar 等底部导航,预留底部空间
 */
const footerHeight = ref(0)

/**
 * 是否已完成高度测量
 * @description 避免重复测量
 */
const heightMeasured = ref(false)

/**
 * 测量头部和底部高度
 * @description 使用 Taro.createSelectorQuery() 动态测量页面元素高度
 */
const measureHeaderHeight = async () => {
  if (heightMeasured.value) return

  try {
    // 获取系统信息
    const systemInfo = await Taro.getSystemInfo()
    const { windowHeight, screenHeight, safeArea } = systemInfo

    // 计算底部安全区域高度
    const bottomSafeArea = screenHeight - safeArea.bottom

    /**
     * 计算底部高度
     * @description 处理底部导航栏、安全区域和额外底部空间
     */
    const calculateFooterHeight = () => {
      let totalFooterHeight = 0

      if (props.hasFooter) {
        // 假设 TabBar 高度约为 50px(小程序标准 TabBar 高度)
        totalFooterHeight = 50 + bottomSafeArea
      } else {
        // 无底部导航,只考虑安全区域
        totalFooterHeight = bottomSafeArea
      }

      // 添加额外底部空间(将 rpx 转换为 px:750rpx 设计宽度标准,rpx / 2 = px)
      if (props.extraBottomSpace > 0) {
        const extraBottomSpacePx = props.extraBottomSpace / 2
        totalFooterHeight += extraBottomSpacePx
      }

      footerHeight.value = totalFooterHeight
      heightMeasured.value = true
    }

    let totalHeaderHeight = 0

    // 如果有头部,测量头部实际高度
    if (props.showHeader) {
      await vueNextTick() // 等待 DOM 渲染完成

      const query = Taro.createSelectorQuery()
      query.select('.load-more-header').boundingClientRect()
      query.exec((res) => {
        if (res && res[0]) {
          totalHeaderHeight = res[0].height
        } else {
          // 如果测量失败,使用默认估算值
          totalHeaderHeight = 178 // 356rpx ≈ 178px
        }

        headerHeight.value = totalHeaderHeight
        calculateFooterHeight()  // 现在可以正确调用了
      })
    } else {
      // 无头部
      calculateFooterHeight()
    }
  } catch (err) {
    console.error('[LoadMoreList] 测量高度失败:', err)
    // 测量失败时使用默认值
    headerHeight.value = props.showHeader ? 178 : 0
    footerHeight.value = props.hasFooter ? 80 : 34 // 约50px TabBar + 30px安全区域
    heightMeasured.value = true
  }
}

// 组件挂载后测量高度
onMounted(() => {
  measureHeaderHeight()
})

/**
 * scroll-view 高度
 * @description 动态计算 scroll-view 的高度,使用运行时测量的实际高度
 */
const scrollHeight = computed(() => {
  if (!heightMeasured.value) {
    // 未完成测量时,使用默认估算值
    const defaultHeaderHeight = props.showHeader ? '178px' : '0px' // 356rpx ≈ 178px
    const defaultFooterHeight = props.hasFooter ? '80px' : '34px'
    return `calc(100vh - ${defaultHeaderHeight} - ${defaultFooterHeight})`
  }

  // 使用测量到的实际高度(转换为 px)
  const headerPx = headerHeight.value
  const footerPx = footerHeight.value

  // 计算滚动高度:视口高度 - 头部高度 - 底部高度
  return `calc(100vh - ${headerPx}px - ${footerPx}px)`
})

/**
 * 获取动画延迟
 * @description 只为每批的前10项使用动画延迟,避免累积延迟
 * @param {number} index - 列表项索引
 * @returns {string} 动画延迟样式
 */
function getAnimationDelay(index) {
  // 只为前10项使用动画延迟,其余立即显示
  if (index < 10) {
    return { animationDelay: `${index * 20}ms` }
  }
  // 第10项以后立即显示(无延迟)
  return {}
}

/**
 * 处理 scroll-view 滚动到底部事件
 * @description 当 scroll-view 滚动到底部时触发
 */
const handleScrollToLower = () => {
  // 如果正在加载或没有更多数据,不执行
  if (props.loadingMore || props.loading || !props.hasMore) {
    return
  }

  const nextPage = props.page + 1
  emit('load-more', nextPage)
}

/**
 * 下拉刷新
 * @description 用户下拉时触发刷新事件,仅当enablePullDownRefresh为true时有效
 */
if (props.enablePullDownRefresh) {
  usePullDownRefresh(() => {
    emit('refresh')
    stopPullDownRefresh()
  })
}

/**
 * 监听 showHeader、hasFooter 和 extraBottomSpace 变化
 * @description 当头部或底部配置变化时,重新测量高度
 */
watch([() => props.showHeader, () => props.hasFooter, () => props.extraBottomSpace], () => {
  heightMeasured.value = false
  measureHeaderHeight()
})

/**
 * 页面显示时重新测量高度
 * @description 确保在页面显示时高度计算正确(处理从其他页面返回的情况)
 */
useDidShow(() => {
  heightMeasured.value = false
  measureHeaderHeight()
})
</script>

<style lang="less">
.load-more-list {
  background-color: #F9FAFB;
  height: 100vh;
  overflow: hidden;
}

.load-more-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #F9FAFB;
}

.load-more-content {
  // 列表容器样式
  width: 100%;
  box-sizing: border-box;
  padding: 32rpx;

  &.no-padding {
    padding: 0;
  }

  // 可滚动状态
  &.scrollable {
    // 高度通过 :style 动态绑定
    box-sizing: border-box;
    // 重置基础 padding,只保留顶部和左右,底部预留空间 + 安全区域
    // 确保在所有设备(包括刘海屏)上"没有更多了"文字都能完整显示
    padding: 32rpx 32rpx calc(env(safe-area-inset-bottom));
  }
}

// 列表容器
.list-container {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  width: 100%;
  box-sizing: border-box;

  // 去除列表项的黑点
  view {
    list-style: none;
  }
}

// 列表项进入动画
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.list-item {
  animation: slideIn 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) backwards;

  // 确保去除列表样式
  list-style: none;
}

// 加载更多容器
.load-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  min-height: 80rpx;
}

.load-more-loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

.load-more-finished {
  display: flex;
  align-items: center;
  justify-content: center;
}

// 自定义加载动画
.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #E5E7EB;
  border-top-color: #4CAF50;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

.loading-spinner-small {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid #E5E7EB;
  border-top-color: #4CAF50;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>