Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue 虚拟列表

作者:潇洒一醉   发布日期:2025-03-23   浏览:72

<template>
  <div class="virtual-list">
    <ul>
      <li v-for="item in visibleItems" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: Array.from({ length: 1000 }, (_, i) => ({ id: i, name: `Item ${i}` })),
      startIndex: 0,
      endIndex: 9,
      itemHeight: 50,
      containerHeight: 500
    };
  },
  computed: {
    visibleItems() {
      return this.items.slice(this.startIndex, this.endIndex + 1);
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      const scrollTop = window.scrollY;
      const start = Math.floor(scrollTop / this.itemHeight);
      const end = start + Math.ceil(this.containerHeight / this.itemHeight);

      this.startIndex = start;
      this.endIndex = end;
    }
  }
};
</script>

<style scoped>
.virtual-list {
  height: 500px;
  overflow-y: auto;
}
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
li {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ccc;
}
</style>

解释说明

  1. 数据准备:

    • items: 包含1000个元素的数组,模拟大数据量。
    • startIndexendIndex: 分别表示当前可见区域的起始和结束索引。
    • itemHeightcontainerHeight: 每个列表项的高度和容器的高度。
  2. 计算属性:

    • visibleItems: 根据 startIndexendIndex 计算当前可见的列表项。
  3. 生命周期钩子:

    • mounted: 添加滚动事件监听器。
    • beforeDestroy: 移除滚动事件监听器,防止内存泄漏。
  4. 方法:

    • handleScroll: 监听滚动事件,根据滚动位置更新 startIndexendIndex,从而动态显示当前可见的列表项。
  5. 样式:

    • 设置 .virtual-list 的高度和溢出属性,确保可以滚动。
    • 设置每个 li 元素的高度和样式,使其一致且美观。

上一篇:datav vue3

下一篇:arttemplate vue

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站