当前位置:首页 > VUE

vue虚拟列表实现

2026-01-19 11:47:16VUE

虚拟列表的实现原理

虚拟列表的核心思想是仅渲染可视区域内的元素,而非整个列表。通过动态计算可视区域的起始和结束索引,减少DOM节点数量,提升性能。关键在于监听滚动事件,动态更新渲染范围。

计算可视区域范围

需要获取容器高度、每个列表项的高度以及当前滚动位置。根据这些数据计算当前可视区域的起始索引和结束索引。

const containerHeight = containerRef.value.clientHeight;
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(
  startIndex + Math.ceil(containerHeight / itemHeight),
  listData.length
);

动态渲染可见项

根据计算得到的startIndex和endIndex,从原始数据中切片获取需要渲染的数据。通过CSS的transform属性对切片后的列表进行偏移,保持滚动位置正确。

const visibleData = computed(() => {
  return listData.slice(startIndex.value, endIndex.value);
});

const listStyle = computed(() => {
  return {
    height: `${listData.length * itemHeight}px`,
    position: 'relative',
  };
});

const itemStyle = (index) => {
  return {
    position: 'absolute',
    top: `${(startIndex.value + index) * itemHeight}px`,
    width: '100%',
  };
};

监听滚动事件

在容器元素上添加滚动事件监听器,实时更新scrollTop值,触发重新计算可见范围。

const handleScroll = (e) => {
  scrollTop.value = e.target.scrollTop;
};

<div class="container" @scroll="handleScroll">
  <div :style="listStyle">
    <div v-for="(item, index) in visibleData" :key="item.id" :style="itemStyle(index)">
      <!-- 列表项内容 -->
    </div>
  </div>
</div>

动态高度处理

如果列表项高度不固定,需要更复杂的实现。可以预先计算或估计每项高度,存储在数组中。滚动时根据实际高度动态调整。

const heights = ref([]);
const getItemHeight = (index) => {
  return heights.value[index] || estimatedHeight;
};

// 在列表项渲染后,测量实际高度并更新
const updateHeight = (index, height) => {
  heights.value[index] = height;
};

性能优化建议

使用Intersection Observer API替代scroll事件监听,减少主线程压力。对于超长列表,可以增加缓冲区,预渲染可视区域外的部分项,减少滚动时的闪烁。

vue虚拟列表实现

const bufferSize = 5;
const startIndexWithBuffer = Math.max(0, startIndex - bufferSize);
const endIndexWithBuffer = Math.min(
  endIndex + bufferSize,
  listData.length
);

标签: 列表vue
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

vue实现报表

vue实现报表

vue实现报表的方法 使用Vue实现报表通常需要结合图表库或表格组件。以下是几种常见方法: 使用ECharts 安装ECharts库: npm install echarts vue-echart…

vue 实现级联

vue 实现级联

Vue 实现级联选择器 级联选择器(Cascader)常用于省市区选择、分类选择等场景。Vue 中可以通过 Element UI、Ant Design Vue 等 UI 库实现,也可以手动封装。 使…

实现简易vue

实现简易vue

实现简易 Vue 的核心思路 Vue 的核心功能包括数据响应式、模板编译和虚拟 DOM。以下是一个简易实现方案,涵盖核心功能模块。 数据响应式系统 通过 Object.defineProperty…

vue实现素材

vue实现素材

Vue 实现素材的方法 使用 Vue 组件管理素材 在 Vue 项目中,可以通过组件化的方式管理素材。创建一个专门的组件来加载和显示素材,例如图片、视频或音频文件。组件可以接收素材的路径或 URL 作…

vue 实现单选

vue 实现单选

使用 v-model 绑定单选值 在 Vue 中,可以通过 v-model 绑定单选按钮的值。定义一个响应式数据(如 selectedOption),并将其与单选按钮的 value 属性关联。…