实现一个vue3的虚拟列表组件,包含加载更多以及loading状态

一. 引言

在很多人的博客中看到虚拟列表,一直都没有好好研究,趁着这次的时间,好好的研究一下了,不知道会不会有人看这篇文章呢?随便吧哈哈哈,未来希望自己能用得上这篇文章哦。

此篇文章主要实现一下定高的虚拟列表,主要是对虚拟列表的思路做一个简单的学习了。

二. Vue3虚拟列表组件的实现

2.1 基本思路

关于虚拟列表的实现,以我的角度出发,分为三步:

  1. 确定截取的数据的起始下标,然后根据起始下标的值计算结束下标
  2. 通过padding值填充未渲染位置,使其能够滑动,同时动态计算paddingTop和paddingBottom
  3. 绑定滚动事件,更新截取的视图列表和padding的值

在这里的话重点在于计算初始的下标,要根据scrollTop属性来计算(之前自己曾写过虚拟列表是根据滚动的改变多少来改变初始下标的,结果滚动非常快的时候,就完全对应不上来了,而通过scrollTop,那么才是稳定的,因为scrollTop的值和滚动条的位置绑定,而滚动条的位置和滚动事件触发的次数是没有唯一性的)

2.2 代码实现

  • 基本的dom结构
<template>
    <div class="scroll-box" ref="scrollBox" @scroll="handleScroll"
    :style="{ height: scrollHeight + 'px' }">
        <div class="virtual-list" :style="{ paddingTop: paddingTop + 'px', paddingBottom: paddingBottom + 'px' }">
            <div v-for="(item, index) in visibleItems" :key="index" :style="{ height: itemHeight + 'px' }">
                <slot name="item" :item="item" :index="index"></slot>
            </div>
        </div>
        <Loading :is-show="isShowLoad" />
    </div>
</template>

此处为了保证列表项能够有更多的自由度,选择使用插槽,在使用的时候需要确保列表项的高度和设定的高度一致哦。

  • 计算paddingTop,paddingBottom,visibleItems
const visibleCount = Math.ceil(props.scrollHeight / props.itemHeight) + 1
const start = ref(0)
const end = computed(() => Math.min(start.value + 2 * visibleCount - 1,renderData.value.length))
const paddingTop = computed(() => start.value * props.itemHeight)
const renderData = ref([...props.listData])
const paddingBottom = computed(() => (renderData.value.length - end.value) * props.itemHeight)
const visibleItems = computed(() => renderData.value.slice(start.value, end.value))

其中scrollHeight是指滑动区域的高度,itemHeight是指列表元素的高度,此处为了避免白屏,将end的值设置为两个屏幕的大小的数据,第二个屏幕作为缓冲区;多定义一个renderData变量是因为后面会有下拉加载更多功能,props的值不方便修改(可以使用v-model,但是感觉不需要,毕竟父元素不需要的列表数据不需要更新)

  • 绑定滚动事件
let lastIndex = start.value;

const handleScroll = rafThrottle(() => {
    onScrollToBottom();
    onScrolling();
});

const onScrolling = () => {
    const scrollTop = scrollBox.value.scrollTop;
    let thisStartIndex = Math.floor(scrollTop / props.itemHeight);
    const isSomeStart = thisStartIndex == lastIndex;
    if (isSomeStart) return;
    const isEndIndexOverListLen = thisStartIndex + 2 * visibleCount - 1 >= renderData.value.length;
    if (isEndIndexOverListLen) {
        thisStartIndex = renderData.value.length - (2 * visibleCount - 1);
    }
    lastIndex = thisStartIndex;
    start.value = thisStartIndex;
}

function rafThrottle(fn) {
    let lock = false;
    return function (...args) {
        if (lock) return;
        lock = true;
        window.requestAnimationFrame(() => {
            fn.apply(args);
            lock = false;
        });
    };
}

其中onScrollToBottom是触底加载更多函数,在后面代码中会知道,这里先忽略,在滚动事件中,根据scrollTop的值计算起始下标satrt,从而更新计算属性paddingTop,paddingBottom,visibleItems,实现虚拟列表,在这里还使用了请求动画帧进行节流优化。

四. 完整组件代码

  • virtualList.vue
<template>
    <div class="scroll-box" ref="scrollBox" @scroll="handleScroll"
    :style="{ height: scrollHeight + 'px' }">
        <div class="virtual-list" :style="{ paddingTop: paddingTop + 'px', paddingBottom: paddingBottom + 'px' }">
            <div v-for="(item, index) in visibleItems" :key="index" :style="{ height: itemHeight + 'px' }">
                <slot name="item" :item="item" :index="index"></slot>
            </div>
        </div>
        <Loading :is-show="isShowLoad" />
    </div>
</template>

<script setup>
import { ref, computed,onMounted,onUnmounted } from 'vue'
import Loading from './Loading.vue';
import { ElMessage } from 'element-plus'
const props = defineProps({
    listData: { type: Array, default: () => [] },
    itemHeight: { type: Number, default: 50 },
    scrollHeight: { type: Number, default: 300 },
    loadMore: { type: Function, required: true }
})

const isShowLoad = ref(false);

const visibleCount = Math.ceil(props.scrollHeight / props.itemHeight) + 1
const start = ref(0)
const end = computed(() => Math.min(start.value + 2 * visibleCount - 1,renderData.value.length))
const paddingTop = computed(() => start.value * props.itemHeight)
const renderData = ref([...props.listData])
const paddingBottom = computed(() => (renderData.value.length - end.value) * props.itemHeight)
const visibleItems = computed(() => renderData.value.slice(start.value, end.value))
const scrollBox = ref(null);
let lastIndex = start.value;

const handleScroll = rafThrottle(() => {
    onScrollToBottom();
    onScrolling();
});

const onScrolling = () => {
    const scrollTop = scrollBox.value.scrollTop;
    let thisStartIndex = Math.floor(scrollTop / props.itemHeight);
    const isSomeStart = thisStartIndex == lastIndex;
    if (isSomeStart) return;
    const isEndIndexOverListLen = thisStartIndex + 2 * visibleCount - 1 >= renderData.value.length;
    if (isEndIndexOverListLen) {
        thisStartIndex = renderData.value.length - (2 * visibleCount - 1);
    }
    lastIndex = thisStartIndex;
    start.value = thisStartIndex;
}

const onScrollToBottom = () => {
    const scrollTop = scrollBox.value.scrollTop;
    const clientHeight = scrollBox.value.clientHeight;
    const scrollHeight = scrollBox.value.scrollHeight;
    if (scrollTop + clientHeight >= scrollHeight) {
        loadMore();
    }
}
let loadingLock = false;
let lockLoadMoreByHideLoading_once = false;
const loadMore = (async () => {
    if (loadingLock) return;
    if (lockLoadMoreByHideLoading_once) {
        lockLoadMoreByHideLoading_once = false;
        return;
    }
    loadingLock = true;
    isShowLoad.value = true;
    const moreData = await props.loadMore().catch(err => {
        console.error(err);
        ElMessage({
            message: '获取数据失败,请检查网络后重试',
            type: 'error',
        })
        return []
    })
    if (moreData.length != 0) {
        renderData.value = [...renderData.value, ...moreData];
        handleScroll();  
    }
    isShowLoad.value = false;
    lockLoadMoreByHideLoading_once = true;
    loadingLock = false;
})

function rafThrottle(fn) {
    let lock = false;
    return function (...args) {
        if (lock) return;
        lock = true;
        window.requestAnimationFrame(() => {
            fn.apply(args);
            lock = false;
        });
    };
}

onMounted(() => {
    scrollBox.value.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
    scrollBox.value.removeEventListener('scroll', handleScroll);
});

</script>

<style scoped>
.virtual-list {
    position: relative;
}
.scroll-box {
    overflow-y: auto;
}
</style>
  • Loading.vue
<template>
    <div class="loading" v-show="pros.isShow">
        <p>Loading...</p>
    </div>
</template>

<script setup>
    const pros = defineProps(['isShow'])
</script>

<style>
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  background-color: #f5f5f5;
}
</style>

以下是使用demo
App.vue

<script setup>
import VirtualList from '@/components/virtualList.vue';

import { onMounted, ref } from 'vue';
let listData = ref([]);
let num = 200;
// 模拟从 API 获取数据
const fetchData = async () => {
  // 这里可以替换成您实际的 API 请求
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      const newData = Array.from({ length: 200 }, (_, index) => `Item ${index}`);
      listData.value = newData;
      resolve();
    }, 500);
  })
}
// 加载更多数据
const loadMore = () => {
  // 这里可以替换成您实际的 API 请求
  return new Promise((resolve) => {
    setTimeout(() => {
      const moreData = Array.from({ length: 30 }, (_, index) => `Item ${num + index}`);
      num += 30;
      resolve(moreData);
    }, 500);
  });
  //模拟请求错误
  // return new Promise((_, reject) => {
  //   setTimeout(() => {
  //     reject('错误模拟');
  //   }, 1000);
  // })
}

onMounted(() => {
   fetchData();
});
</script>

<template>
  <!-- class="virtualContainer" -->
  <VirtualList v-if="listData.length > 0"
      
     :listData="listData" :itemHeight="50" :scrollHeight="600" :loadMore="loadMore">
      <template #item="{ item,index }">
        <div class="list-item">
          {{  item }}
        </div>
      </template>
  </VirtualList>
</template>

<style scoped>
.list-item {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ccc;
  text-align: center;
}
</style>

此处添加了常用的加载更多和loading以及错误提示,这样会更加的全面一些,总体上应该还是挺满足很多实际的?如果你看了我的文章,觉得还可以,但是还是和自己的需求出入有些大,欢迎批评指正!!!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3提供了一个新的组件API,使得构建虚拟列表变得更加容易。下面是一个简单的实现示例: 1. 安装依赖: ```bash npm install vue@next npm install vue3-virtual-scroll-list ``` 2. 在组件中使用虚拟列表: ```vue <template> <virtual-scroll-list :size="50" :remain="20" :data-key="'id'" :data-sources="items" @scroll="handleScroll" > <template v-slot="{ data }"> <div v-for="item in data" :key="item.id">{{ item.text }}</div> </template> </virtual-scroll-list> </template> <script> import { ref } from 'vue' import VirtualScrollList from 'vue3-virtual-scroll-list' export default { components: { VirtualScrollList, }, setup() { const items = ref([]) // 初始化数据 for (let i = 0; i < 10000; i++) { items.value.push({ id: i, text: `Item ${i}`, }) } const handleScroll = (scrollTop) => { // 处理滚动事件 console.log(scrollTop) } return { items, handleScroll, } }, } </script> ``` 在这个示例中,我们使用 `vue3-virtual-scroll-list` 组件实现虚拟列表。这个组件需要传入一些参数,包括: - `size`:每个项的高度 - `remain`:上下额外渲染项的数量 - `data-key`:数据中每个项的唯一标识符 - `data-sources`:数据源 - `scroll`:滚动事件的回调函数 在模板中,我们使用插槽来渲染每个项。同时,组件还会将已经渲染的项缓存起来,以提高性能。 在 `setup` 函数中,我们初始化了一个 `items` 的响应式变量,并将它传入 `data-sources` 中。我们还定义了一个 `handleScroll` 函数来处理滚动事件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值