虚拟列表组件化

This commit is contained in:
2024-12-11 12:08:49 +08:00
parent a0c7bbfd27
commit 9af3b116d1
2 changed files with 372 additions and 269 deletions

View File

@@ -1,289 +1,51 @@
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import VirtualList from './components/VirtualList.vue'
/**
* 虚拟列表配置参数
*/
const CONFIG = {
itemHeight: 50, // 列表项基础高度
itemPadding: 16, // 列表项上下padding总和(8px * 2)
bufferCount: 2, // 上下缓冲区域的项目数量
scrollDebounceTime: 16 // 滚动防抖时间(一帧)
// 虚拟列表配置
const listConfig = {
itemHeight: 50,
itemPadding: 16,
bufferCount: 2,
scrollDebounceTime: 16,
}
// 计算列表项实际总高度
const totalItemHeight = CONFIG.itemHeight + CONFIG.itemPadding
/**
* 响应式状态管理
*/
const containerHeight = ref(0) // 容器高度
const startIndex = ref(0) // 可视区域起始索引
const selectedIndex = ref(0) // 当前选中项索引
const isKeyboardNavigating = ref(false) // 键盘导航状态
let keyboardTimer = null // 键盘导航定时器
/**
* DOM 引用
*/
const containerRef = ref(null)
const listRef = ref(null)
/**
* 生成模拟数据
* @returns {Array} 包含100条模拟项目数据的数组
*/
// 生成模拟数据
const listData = Array.from({ length: 100 }, (_, i) => ({
id: i,
name: `project-${i + 1}`,
path: `/Users/lanyuanxiaoyao/Project/IdeaProjects/project-${i + 1}`
path: `/Users/lanyuanxiaoyao/Project/IdeaProjects/project-${i + 1}`,
}))
/**
* 计算属性
*/
// 计算可视区域能显示的列表项数量
const visibleCount = computed(() =>
Math.floor(containerHeight.value / totalItemHeight)
)
// 计算当前需要渲染的数据
const visibleData = computed(() => {
const visibleStart = Math.max(0, startIndex.value - CONFIG.bufferCount)
const visibleEnd = Math.min(
listData.length,
startIndex.value + visibleCount.value + CONFIG.bufferCount
)
return listData.slice(visibleStart, visibleEnd).map((item, index) => ({
...item,
index: visibleStart + index
}))
})
// 计算列表偏移量
const offsetY = computed(() =>
Math.max(0, (startIndex.value - CONFIG.bufferCount) * totalItemHeight)
)
// 计算虚拟列表总高度
const phantomHeight = computed(() =>
listData.length * totalItemHeight
)
/**
* 工具函数
*/
// 防抖函数
const debounce = (fn, delay) => {
let timer = null
return (...args) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => fn.apply(null, args), delay)
}
// 选择处理
const handleSelect = (item) => {
console.log('Selected:', item)
}
/**
* 事件处理函数
*/
// 更新容器高度
const updateContainerHeight = () => {
containerHeight.value = window.innerHeight
}
// 滚动处理
const handleScroll = debounce(() => {
if (!containerRef.value) return
const scrollTop = containerRef.value.scrollTop
const newStartIndex = Math.floor(scrollTop / totalItemHeight)
if (newStartIndex !== startIndex.value) {
startIndex.value = newStartIndex
}
}, CONFIG.scrollDebounceTime)
// 鼠标移入处理
const handleMouseEnter = (index) => {
if (!isKeyboardNavigating.value) {
selectedIndex.value = index
ensureSelectedItemVisible()
}
}
// 键盘导航处理
const handleKeyDown = (e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
e.preventDefault()
isKeyboardNavigating.value = true
if (keyboardTimer) clearTimeout(keyboardTimer)
const containerTop = containerRef.value.scrollTop
const currentVisibleStartIndex = Math.floor(containerTop / totalItemHeight)
const currentVisibleEndIndex = currentVisibleStartIndex + visibleCount.value - 1
const nextIndex = e.key === 'ArrowUp'
? Math.max(0, selectedIndex.value - 1)
: Math.min(listData.length - 1, selectedIndex.value + 1)
// 自动滚动到可视区域
if (nextIndex <= currentVisibleStartIndex) {
containerRef.value.scrollTop = nextIndex * totalItemHeight
} else if (nextIndex > currentVisibleEndIndex) {
containerRef.value.scrollTop = (nextIndex - visibleCount.value + 1) * totalItemHeight
}
selectedIndex.value = nextIndex
keyboardTimer = setTimeout(() => {
isKeyboardNavigating.value = false
}, 1000)
}
// 确保选中项在可视区域内
const ensureSelectedItemVisible = () => {
if (!containerRef.value) return
const containerTop = containerRef.value.scrollTop
const containerHeight = containerRef.value.clientHeight
const visibleCount = Math.floor(containerHeight / totalItemHeight)
const currentVisibleStartIndex = Math.floor(containerTop / totalItemHeight)
const currentVisibleEndIndex = currentVisibleStartIndex + visibleCount - 1
if (selectedIndex.value < currentVisibleStartIndex) {
containerRef.value.scrollTop = selectedIndex.value * totalItemHeight
} else if (selectedIndex.value > currentVisibleEndIndex) {
containerRef.value.scrollTop = (selectedIndex.value - visibleCount + 1) * totalItemHeight
}
}
/**
* 生命周期钩子
*/
onMounted(() => {
if (containerRef.value) {
containerRef.value.addEventListener('scroll', handleScroll)
}
updateContainerHeight()
window.addEventListener('resize', updateContainerHeight)
window.addEventListener('keydown', handleKeyDown)
})
onBeforeUnmount(() => {
if (containerRef.value) {
containerRef.value.removeEventListener('scroll', handleScroll)
}
window.removeEventListener('resize', updateContainerHeight)
window.removeEventListener('keydown', handleKeyDown)
if (keyboardTimer) {
clearTimeout(keyboardTimer)
}
})
</script>
<template>
<!-- 原有的虚拟列表容器 -->
<div
ref="containerRef"
class="virtual-list-container"
:style="{ height: `${containerHeight}px` }"
tabindex="0"
>
<div
ref="listRef"
class="virtual-list-phantom"
:style="{ height: `${phantomHeight}px` }"
>
<div
class="virtual-list"
:style="{ transform: `translateY(${offsetY}px)` }"
>
<div
v-for="item in visibleData"
:key="item.index"
class="list-item"
:class="{ 'selected': selectedIndex === item.index }"
:style="{ height: `${CONFIG.itemHeight}px` }"
@mouseenter="handleMouseEnter(item.index)"
>
<div class="item-icon">
<svg viewBox="0 0 24 24" width="16" height="16">
<circle cx="12" cy="12" r="10" fill="#1a1a1a" />
</svg>
</div>
<div class="item-content">
<div class="item-name">{{ item.name }}</div>
<div class="item-path">{{ item.path }}</div>
</div>
</div>
</div>
</div>
<div class="app-container">
<VirtualList
:data="listData"
:config="listConfig"
@select="handleSelect"
/>
</div>
</template>
<style scoped>
.virtual-list-container {
overflow-y: auto;
border: 1px solid #ccc;
position: relative;
background-color: #f4f4f4;
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
}
.virtual-list-phantom {
position: relative;
width: 100%;
}
.virtual-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.list-item {
padding: 8px 16px;
display: flex;
align-items: center;
gap: 12px;
border-bottom: 1px solid #e8e8e8;
transition: background-color 0.2s;
cursor: pointer;
background-color: white;
}
.list-item.selected {
background-color: #e6f7ff;
}
.item-icon {
flex-shrink: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
}
.item-content {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.item-name {
font-size: 14px;
color: #1a1a1a;
font-weight: 500;
}
.item-path {
font-size: 12px;
color: #666;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
#app {
height: 100%;
}
</style>
<style scoped>
.app-container {
height: 100%;
}
</style>

View File

@@ -0,0 +1,341 @@
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
const props = defineProps({
// 列表数据
data: {
type: Array,
required: true
},
// 配置参数
config: {
type: Object,
default: () => ({
itemHeight: 50, // 列表项基础高度
itemPadding: 16, // 列表项上下padding总和
bufferCount: 2, // 上下缓冲区域的项目数量
scrollDebounceTime: 16 // 滚动防抖时间
})
},
// 容器高度
height: {
type: [String, Number],
default: '100%'
}
})
const emit = defineEmits(['select'])
// 计算列表项实际总高度
const totalItemHeight = computed(() =>
props.config.itemHeight + props.config.itemPadding
)
/**
* 响应式状态管理
*/
const containerHeight = ref(0) // 容器高度
const startIndex = ref(0) // 可视区域起始索引
const selectedIndex = ref(0) // 当前选中项索引
const isKeyboardNavigating = ref(false) // 键盘导航状态
let keyboardTimer = null // 键盘导航定时器
/**
* DOM 引用
*/
const containerRef = ref(null)
const listRef = ref(null)
/**
* 计算属性
*/
// 计算可区域能显示的列表项数量
const visibleCount = computed(() =>
Math.floor(containerHeight.value / totalItemHeight.value)
)
// 计算当前需要渲染的数据
const visibleData = computed(() => {
const visibleStart = Math.max(0, startIndex.value - props.config.bufferCount)
const visibleEnd = Math.min(
props.data.length,
startIndex.value + visibleCount.value + props.config.bufferCount
)
return props.data.slice(visibleStart, visibleEnd).map((item, index) => ({
...item,
index: visibleStart + index
}))
})
// 计算列表偏移量
const offsetY = computed(() =>
Math.max(0, (startIndex.value - props.config.bufferCount) * totalItemHeight.value)
)
// 计算虚拟列表总高度
const phantomHeight = computed(() =>
props.data.length * totalItemHeight.value
)
// ... 其他方法保持不变,只需将 CONFIG 替换为 props.config ...
// 选择处理
const handleSelect = (item) => {
selectedIndex.value = item.index
emit('select', item)
}
// 修改更新容器高度的方法
function updateContainerHeight() {
if (containerRef.value) {
const parentHeight = containerRef.value.parentElement?.clientHeight
containerHeight.value = parentHeight || window.innerHeight
}
}
// 添加 ResizeObserver 来监听父容器尺寸变化
let resizeObserver = null
// 添加防抖函数
function debounce(fn, delay) {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
// 滚动处理
const handleScroll = debounce(() => {
if (!containerRef.value) return
const scrollTop = containerRef.value.scrollTop
// 计算新的起始索引
const newStartIndex = Math.floor(scrollTop / totalItemHeight.value)
// 只有当起始索引发生变化时才更新
if (newStartIndex !== startIndex.value) {
startIndex.value = newStartIndex
}
}, props.config.scrollDebounceTime)
// 鼠标移入处理
function handleMouseEnter(index) {
if (!isKeyboardNavigating.value) {
selectedIndex.value = index
ensureSelectedItemVisible()
}
}
// 键盘事件处理
function handleKeyDown(e) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault()
isKeyboardNavigating.value = true
if (keyboardTimer) clearTimeout(keyboardTimer)
const containerTop = containerRef.value.scrollTop
const currentVisibleStartIndex = Math.floor(containerTop / totalItemHeight.value)
const currentVisibleEndIndex = currentVisibleStartIndex + visibleCount.value - 1
if (e.key === 'ArrowUp') {
const nextIndex = Math.max(0, selectedIndex.value - 1)
if (nextIndex <= currentVisibleStartIndex) {
containerRef.value.scrollTop = nextIndex * totalItemHeight.value
}
selectedIndex.value = nextIndex
} else {
const nextIndex = Math.min(props.data.length - 1, selectedIndex.value + 1)
if (nextIndex > currentVisibleEndIndex) {
containerRef.value.scrollTop = (nextIndex - visibleCount.value + 1) * totalItemHeight.value
}
selectedIndex.value = nextIndex
}
keyboardTimer = setTimeout(() => {
isKeyboardNavigating.value = false
}, 1000)
}
}
// 确保选中项可见
function ensureSelectedItemVisible() {
if (!containerRef.value) return
const containerTop = containerRef.value.scrollTop
const containerHeight = containerRef.value.clientHeight
const visibleCount = Math.floor(containerHeight / totalItemHeight.value)
const currentVisibleStartIndex = Math.floor(containerTop / totalItemHeight.value)
const currentVisibleEndIndex = currentVisibleStartIndex + visibleCount - 1
if (selectedIndex.value < currentVisibleStartIndex) {
containerRef.value.scrollTop = selectedIndex.value * totalItemHeight.value
} else if (selectedIndex.value > currentVisibleEndIndex) {
containerRef.value.scrollTop = (selectedIndex.value - visibleCount + 1) * totalItemHeight.value
}
}
onMounted(() => {
if (containerRef.value) {
containerRef.value.addEventListener('scroll', handleScroll)
// 创建 ResizeObserver 监听父容器尺寸变化
resizeObserver = new ResizeObserver(() => {
updateContainerHeight()
})
if (containerRef.value.parentElement) {
resizeObserver.observe(containerRef.value.parentElement)
}
}
updateContainerHeight()
window.addEventListener('resize', updateContainerHeight)
window.addEventListener('keydown', handleKeyDown)
})
onBeforeUnmount(() => {
if (containerRef.value) {
containerRef.value.removeEventListener('scroll', handleScroll)
}
// 清理 ResizeObserver
if (resizeObserver) {
resizeObserver.disconnect()
}
window.removeEventListener('resize', updateContainerHeight)
window.removeEventListener('keydown', handleKeyDown)
if (keyboardTimer) {
clearTimeout(keyboardTimer)
}
})
</script>
<template>
<div
ref="containerRef"
class="virtual-list-container"
:style="{ height: '100%' }"
tabindex="0"
>
<div
ref="listRef"
class="virtual-list-phantom"
:style="{ height: `${phantomHeight}px` }"
>
<div
class="virtual-list"
:style="{ transform: `translateY(${offsetY}px)` }"
>
<div
v-for="item in visibleData"
:key="item.index"
class="list-item"
:class="{ 'selected': selectedIndex === item.index }"
:style="{ height: `${config.itemHeight}px` }"
@mouseenter="handleMouseEnter(item.index)"
@click="handleSelect(item)"
>
<slot name="item" :item="item">
<!-- 默认列表项样式 -->
<div class="default-item">
<div class="item-icon">
<svg viewBox="0 0 24 24" width="16" height="16">
<circle cx="12" cy="12" r="10" fill="#1a1a1a" />
</svg>
</div>
<div class="item-content">
<div class="item-name">{{ item.name }}</div>
<div class="item-path">{{ item.path }}</div>
</div>
</div>
</slot>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.virtual-list-container {
overflow-y: auto;
border: 1px solid #ccc;
position: relative;
background-color: #f4f4f4;
width: 100%;
height: 100%;
}
.virtual-list-phantom {
position: relative;
width: 100%;
}
.virtual-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.list-item {
padding: 8px 16px;
display: flex;
align-items: center;
border-bottom: 1px solid #e8e8e8;
transition: background-color 0.2s;
cursor: pointer;
background-color: white;
}
.list-item.selected {
background-color: #e6f7ff;
}
/* 默认列表项样式 */
.default-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
}
.item-icon {
flex-shrink: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
}
.item-content {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.item-name {
font-size: 14px;
color: #1a1a1a;
font-weight: 500;
}
.item-path {
font-size: 12px;
color: #666;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>