最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解vue3中虛擬列表組件的實(shí)現(xiàn)

 更新時(shí)間:2023年10月09日 14:15:05   作者:摸魚小豆  
這篇文章主要為大家詳細(xì)介紹了vue3中實(shí)現(xiàn)虛擬列表組件的相關(guān)知識(shí),包含加載更多以及l(fā)oading狀態(tài),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下

一. 引言

在很多人的博客中看到虛擬列表,一直都沒有好好研究,趁著這次的時(shí)間,好好的研究一下了,不知道會(huì)不會(huì)有人看這篇文章呢?隨便吧哈哈哈,未來希望自己能用得上這篇文章哦。

此篇文章主要實(shí)現(xiàn)一下定高的虛擬列表,主要是對(duì)虛擬列表的思路做一個(gè)簡(jiǎn)單的學(xué)習(xí)了。

二. Vue3虛擬列表組件的實(shí)現(xiàn)

2.1 基本思路

關(guān)于虛擬列表的實(shí)現(xiàn),以我的角度出發(fā),分為三步:

  • 確定截取的數(shù)據(jù)的起始下標(biāo),然后根據(jù)起始下標(biāo)的值計(jì)算結(jié)束下標(biāo)
  • 通過padding值填充未渲染位置,使其能夠滑動(dòng),同時(shí)動(dòng)態(tài)計(jì)算paddingTop和paddingBottom
  • 綁定滾動(dòng)事件,更新截取的視圖列表和padding的值

在這里的話重點(diǎn)在于計(jì)算初始的下標(biāo),要根據(jù)scrollTop屬性來計(jì)算(之前自己曾寫過虛擬列表是根據(jù)滾動(dòng)的改變多少來改變初始下標(biāo)的,結(jié)果滾動(dòng)非??斓臅r(shí)候,就完全對(duì)應(yīng)不上來了,而通過scrollTop,那么才是穩(wěn)定的,因?yàn)閟crollTop的值和滾動(dòng)條的位置綁定,而滾動(dòng)條的位置和滾動(dòng)事件觸發(fā)的次數(shù)是沒有唯一性的)

2.2 代碼實(shí)現(xiàn)

基本的dom結(jié)構(gòu)

<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>

此處為了保證列表項(xiàng)能夠有更多的自由度,選擇使用插槽,在使用的時(shí)候需要確保列表項(xiàng)的高度和設(shè)定的高度一致哦。

計(jì)算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是指滑動(dòng)區(qū)域的高度,itemHeight是指列表元素的高度,此處為了避免白屏,將end的值設(shè)置為兩個(gè)屏幕的大小的數(shù)據(jù),第二個(gè)屏幕作為緩沖區(qū);多定義一個(gè)renderData變量是因?yàn)楹竺鏁?huì)有下拉加載更多功能,props的值不方便修改(可以使用v-model,但是感覺不需要,畢竟父元素不需要的列表數(shù)據(jù)不需要更新)

綁定滾動(dòng)事件

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是觸底加載更多函數(shù),在后面代碼中會(huì)知道,這里先忽略,在滾動(dòng)事件中,根據(jù)scrollTop的值計(jì)算起始下標(biāo)satrt,從而更新計(jì)算屬性paddingTop,paddingBottom,visibleItems,實(shí)現(xiàn)虛擬列表,在這里還使用了請(qǐng)求動(dòng)畫幀進(jìn)行節(jié)流優(yōu)化。

三. 完整組件代碼

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: '獲取數(shù)據(jù)失敗,請(qǐng)檢查網(wǎng)絡(luò)后重試',
            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 獲取數(shù)據(jù)
const fetchData = async () => {
  // 這里可以替換成您實(shí)際的 API 請(qǐng)求
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      const newData = Array.from({ length: 200 }, (_, index) => `Item ${index}`);
      listData.value = newData;
      resolve();
    }, 500);
  })
}
// 加載更多數(shù)據(jù)
const loadMore = () => {
  // 這里可以替換成您實(shí)際的 API 請(qǐng)求
  return new Promise((resolve) => {
    setTimeout(() => {
      const moreData = Array.from({ length: 30 }, (_, index) => `Item ${num + index}`);
      num += 30;
      resolve(moreData);
    }, 500);
  });
  //模擬請(qǐng)求錯(cuò)誤
  // return new Promise((_, reject) => {
  //   setTimeout(() => {
  //     reject('錯(cuò)誤模擬');
  //   }, 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以及錯(cuò)誤提示,這樣會(huì)更加的全面一些,總體上應(yīng)該還是挺滿足很多實(shí)際的。

到此這篇關(guān)于詳解vue3中虛擬列表組件的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)vue3虛擬列表組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

涿鹿县| 武冈市| 肥城市| 绍兴市| 江孜县| 德安县| 南雄市| 栖霞市| 铜山县| 漾濞| 大丰市| 蒙阴县| 伊川县| 洞头县| 锡林郭勒盟| 历史| 桂林市| 蓬溪县| 麦盖提县| 平阳县| 泌阳县| 仁怀市| 靖边县| 高青县| 平江县| 平定县| 岳西县| 关岭| 临沭县| 鹤山市| 西林县| 瑞丽市| 吉林省| 柘城县| 马公市| 神农架林区| 得荣县| 九龙县| 穆棱市| 临高县| 清流县|