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

vue 虚拟滚动

作者:独夜无伴   发布日期:2026-07-19   浏览:23

<template>
  <div class="virtual-scroll-container" ref="container">
    <div class="scrollable-content" :style="{ transform: `translateY(${offset}px)` }">
      <div v-for="item in visibleItems" :key="item.id" class="item">
        {{ item.content }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: Array.from({ length: 1000 }, (_, i) => ({ id: i, content: `Item ${i + 1}` })),
      containerHeight: 300,
      itemHeight: 50,
      visibleCount: 0,
      startIndex: 0,
      offset: 0
    };
  },
  computed: {
    visibleItems() {
      return this.items.slice(this.startIndex, this.startIndex + this.visibleCount);
    }
  },
  mounted() {
    this.$refs.container.addEventListener('scroll', this.handleScroll);
    this.updateVisibleItems();
  },
  methods: {
    updateVisibleItems() {
      this.visibleCount = Math.ceil(this.$refs.container.clientHeight / this.itemHeight) + 2;
      this.startIndex = Math.floor(this.$refs.container.scrollTop / this.itemHeight);
      this.offset = this.startIndex * this.itemHeight - this.$refs.container.scrollTop;
    },
    handleScroll() {
      this.updateVisibleItems();
    }
  },
  beforeDestroy() {
    this.$refs.container.removeEventListener('scroll', this.handleScroll);
  }
};
</script>

<style scoped>
.virtual-scroll-container {
  height: 300px;
  overflow-y: auto;
}
.scrollable-content {
  transition: transform 0.1s ease-out;
}
.item {
  height: 50px;
  border-bottom: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

解释说明

  1. 模板部分 (<template>):

    • 使用一个 div 容器来包裹所有可滚动的内容。
    • scrollable-content 是实际包含内容的容器,通过 CSS 的 transform 属性实现平滑滚动。
    • v-for 指令用于渲染当前可见的项。
  2. 脚本部分 (<script>):

    • data 中定义了虚拟滚动所需的数据:
      • items: 模拟的大量数据。
      • containerHeight: 容器的高度。
      • itemHeight: 每个项的高度。
      • visibleCount: 当前可见的项数。
      • startIndex: 当前显示项的起始索引。
      • offset: 用于计算偏移量。
    • computed 计算属性 visibleItems 返回当前可见的项。
    • mounted 生命周期钩子中添加滚动事件监听,并初始化可见项。
    • methods 中定义了更新可见项和处理滚动事件的方法。
    • beforeDestroy 生命周期钩子中移除滚动事件监听。
  3. 样式部分 (<style scoped>):

    • 设置容器高度和滚动条样式。
    • 设置每个项的高度和边框样式。
    • 使用 transition 实现平滑滚动效果。

上一篇:vue 时间戳

下一篇:vue3安装scss

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js transpi

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

Laravel 中文站