Skip to content

FixedVirtualList 固定高度虚拟列表

固定高度虚拟列表组件,用于高效渲染大量数据。适用于条目高度(或宽度)固定不变的场景,通过只渲染可视区域内的条目来提升性能。

导入

js
import FixedVirtualList from '@/components/list/FixedVirtualList.vue';

使用方法

基础用法

以下是一个基础的垂直滚动虚拟列表示例。

INFO

提示:对于小程序,特别是微信小程序,不支持scop slot,需要在调用者组件中渲染条目,不支持使用 item 插槽。

vue
<template>
  <FlexCol position="relative" flex="1 1 0%">
    <!-- 非小程序环境 -->
    <!-- #ifndef MP -->
    <FixedVirtualList
      ref="virtualList"
      :data="list"
      :itemSize="50"
      :width="'100%'"
      :height="300"
      @scroll="onScroll"
    >
      <template #item="{ item, index }">
        <div class="list-item">
          <span class="index">{{ index }}</span>
          <span class="content">{{ item.content }}</span>
        </div>
      </template>
    </FixedVirtualList>
    <!-- #endif -->

    <!-- 小程序环境 -->
    <!-- #ifdef MP -->
    <FixedVirtualList
      ref="virtualList"
      :data="list"
      :itemSize="50"
      :width="'100%'"
      :height="300"
      @scroll="onScroll"
    >
      <!-- 对于小程序,特别是微信小程序,不支持scop slot,需要在调用者组件中渲染条目 -->
      <template #list="{ visibleItems, className, itemStyle }">
        <view 
          v-for="row in visibleItems" 
          :key="row.key"
          :style="itemStyle"
          :class="className"
        >
          <Cell :title="row.item.title" bottomBorder showArrow />
        </view>
      </template>
    </FixedVirtualList>
    <!-- #endif -->
  </FlexCol>
</template>

<script>
import FixedVirtualList from '@/components/list/FixedVirtualList.vue';

export default {
  components: {
    FixedVirtualList
  },
  data() {
    return {
      list: [],
    };
  },
  onMounted() {
    // 生成1000条示例数据
    this.list = Array.from({ length: 1000 }, (_, index) => ({
      id: index,
      content: `项目 ${index + 1}`
    })); 
    // 手动更新容器尺寸(在某些情况下可能需要)
    // this.$nextTick(() => {
    //   this.$refs.virtualList?.updateContainerSizeAndFlush();
    // });
  },
  methods: {
    onScroll(event) {
      console.log('滚动信息:', event);
    }
  }
};
</script>

API 参考

Props

参数名类型默认值说明
dataArray[]列表数据数组
itemSizeNumber必填每个条目的高度(垂直滚动)或宽度(水平滚动)
heightNumber | String300列表容器高度
widthNumber | String'100%'列表容器宽度
dataKeyStringundefined数据项的唯一键名,用于vue循环优化
directionString'vertical'滚动方向,可选值:'vertical','horizontal'
bufferSizeNumber5缓冲区大小(可视区域外额外渲染的条目数量)
containerStyleObject{ height: '100%', width: '100%' }容器样式

Slots

插槽名参数说明
item{ item, index }列表项插槽,接收当前项数据和索引(仅非小程序环境)
list{ visibleItems, className, itemStyle }列表容器插槽,接收可见的条目数据
inner-内部插槽
prefix-前缀插槽
suffix-后缀插槽
empty-空状态插槽,当data为空时显示

Events

事件名回调参数说明
scrollevent滚动事件,返回原生滚动事件对象

暴露的方法

方法名参数返回值说明
updateContainerSizeAndFlush-void更新容器尺寸并刷新列表

主题变量

本组件无主题变量。