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

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

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

一. 引言

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

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

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

2.1 基本思路

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

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

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

2.2 代碼實現(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>

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

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

綁定滾動事件

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ù),在后面代碼中會知道,這里先忽略,在滾動事件中,根據(jù)scrollTop的值計算起始下標(biāo)satrt,從而更新計算屬性paddingTop,paddingBottom,visibleItems,實現(xiàn)虛擬列表,在這里還使用了請求動畫幀進(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ù)失敗,請檢查網(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 () => {
  // 這里可以替換成您實際的 API 請求
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      const newData = Array.from({ length: 200 }, (_, index) => `Item ${index}`);
      listData.value = newData;
      resolve();
    }, 500);
  })
}
// 加載更多數(shù)據(jù)
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以及錯誤提示,這樣會更加的全面一些,總體上應(yīng)該還是挺滿足很多實際的。

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

相關(guān)文章

最新評論

玉溪市| 凯里市| 邢台市| 丹阳市| 民勤县| 英德市| 朝阳市| 长兴县| 沈阳市| 汾西县| 利川市| 平顺县| 哈密市| 邻水| 呼伦贝尔市| 万年县| 岗巴县| 吕梁市| 太白县| 武鸣县| 新郑市| 赤水市| 麻阳| 吴江市| 广德县| 宁蒗| 枣阳市| 鹤峰县| 乳源| 右玉县| 临朐县| 西丰县| 尼玛县| 大连市| 邵阳县| 玉屏| 彭泽县| 太白县| 木兰县| 宜丰县| 资阳市|