vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue虚拟滚动/虚拟列表

vue虚拟滚动/虚拟列表简单实现示例

作者:llh_fzl

本文主要介绍了vue虚拟滚动/虚拟列表简单实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

App.vue

<template>
  <div class="container">
    <virtual-list :data="data"/>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import VirtualList from './components/VirtualList.vue';

const data = reactive((() => {
  const arr = [];
  for (let i = 0; i < 1000000; i++) arr[i] = i;
  return arr;
})());
</script>

<style scoped>
.container {
  width: 400px;
  height: 400px;
}
</style>

virtual-list.vue

<template>
  <div
    class="view"
    :ref="el => viewRef = el"
    @scroll="handleScroll"
  >
    <div
      class="phantom"
      :style="{ height: `${itemSize * data.length}px` }"
    >
    </div>
    <div
      class="list"
      :style="{ transform: `translateY(${translateLen}px)` }"
    >
      <div
        v-for="item in visibleList"
        :style="{ height: `${itemSize}px` }"
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';

const props = defineProps({
  data: {
    type: Array,
    default: [],
  },
  itemSize: {
    type: Number,
    default: 32,
  }
})

const translateLen = ref(0);

const viewRef = ref(null);

const start = ref(0);
const visibleCount = computed(() => Math.ceil((viewRef.value?.clientHeight ?? 0) / props.itemSize));
const visibleList = computed(() => props.data.slice(start.value, start.value + visibleCount.value));

const handleScroll = () => {
  const scrollTop = viewRef.value.scrollTop;
  start.value = Math.floor(scrollTop / props.itemSize);

  translateLen.value = scrollTop - (scrollTop % props.itemSize);
}

</script>

<style scoped>
.view {
  position: relative;
  height: 100%;
  overflow: auto;
}

.phantom {
  position: absolute;
  width: 100%;
}

.list {
  position: absolute;
}
</style>

tip

到此这篇关于vue虚拟滚动/虚拟列表简单实现示例的文章就介绍到这了,更多相关vue虚拟滚动/虚拟列表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文