vue虛擬滾動/虛擬列表簡單實現(xiàn)示例
更新時間:2025年01月10日 09:30:48 作者:llh_fzl
本文主要介紹了vue虛擬滾動/虛擬列表簡單實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
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
- item的高度保持一致
- phantom用于顯示一致的滾動條
- list部分通過translate顯示在視區(qū)內(nèi)
到此這篇關(guān)于vue虛擬滾動/虛擬列表簡單實現(xiàn)示例的文章就介紹到這了,更多相關(guān)vue虛擬滾動/虛擬列表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue?elementUI表單嵌套表格并對每行進(jìn)行校驗詳解
element-ui中有詳細(xì)的各種表格及表格方法,下面這篇文章主要給大家介紹了關(guān)于Vue?elementUI表單嵌套表格并對每行進(jìn)行校驗的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-01-01
Vue 2.0學(xué)習(xí)筆記之Vue中的computed屬性
本篇文章主要介紹了Vue 2.0學(xué)習(xí)筆記之Vue中的computed屬性,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
vue3編譯報錯ESLint:defineProps is not defined&nbs
這篇文章主要介紹了vue3編譯報錯ESLint:defineProps is not defined no-undef的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
基于vue實現(xiàn)網(wǎng)站前臺的權(quán)限管理(前后端分離實踐)
這篇文章主要介紹了基于vue實現(xiàn)網(wǎng)站前臺的權(quán)限管理(前后端分離實踐),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
vue draggable resizable 實現(xiàn)可拖拽縮放的組件功能
這篇文章主要介紹了vue draggable resizable 實現(xiàn)可拖拽縮放的組件功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07

