useVirtualList
管理虚拟列表
Demo
0
1
2
3
4
5
6
7
8
9
Usage
html
<template>
<div>
<div
:ref="containerProps.ref"
@scroll="containerProps.onScroll"
style="height: 300px; overflow: auto; border: 1px solid #cccccc"
>
<div :style="wrapperStyle">
<div
v-for="active in list"
:key="active"
style="
height: 60px;
border-bottom: 1px solid #cccccc;
background-color: white;
"
>
{{ active }}
</div>
</div>
</div>
<button type="button" @click="handleVirtualScrollTo">
scroll to
</button>
</div>
</template>
<script lang="ts" setup>
import { useVirtualList } from '@morehook/core'
const { list, wrapperStyle, containerProps, scrollTo } = useVirtualList(
Array.from(Array(99999).keys()),
{ itemHeight: 60, overscan: 10 }
)
// 滚动到第22个元素
const handleVirtualScrollTo = () => {
scrollTo(22)
}
</script>
Type Declarations
typescript
/**
* itemHeight: 列表中子项的高度
* overscan: 滚动列表时为了让视图正常设置的偏差值 (默认为5,一般情况下不需要特殊设置)
*/
export interface Option {
itemHeight: number | ((index: number) => number)
overscan?: number
}
/**
* 虚拟列表
* @param state 源数据
* @param options Option
* @returns
* list: 当前视图显示的数据
* wrapperStyle: 包装列表的容器样式
* containerProps: 最外层容器的ref以及scroll事件绑定
*/
export declare function useVirtualList<T = any>(
state: T[],
options: Option
): {
list: Ref<T[]>
wrapperStyle: {
width: string
height: string
marginTop: string
}
containerProps: {
ref: (ele: any) => void
onScroll: (e: any) => void
style: {
overflowY: "auto"
}
}
scrollTo: (index: number) => void
}