优化参数配置,简化组件构建

This commit is contained in:
2024-12-11 15:40:44 +08:00
parent 812a642aaa
commit 0a8af1d97b
4 changed files with 31 additions and 51 deletions

View File

@@ -1,10 +1,9 @@
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import type { ListItem, ListConfig } from '@/types'
import type { ListItem } from '@/types'
interface Props {
data: ListItem[]
config: ListConfig
height?: string | number
frozen?: boolean
disableHover?: boolean
@@ -23,9 +22,19 @@ const emit = defineEmits<{
showToast: [message: string]
}>()
// ===== 列表配置常量 =====
/** 列表项基础高度(像素) */
const ITEM_HEIGHT = 50
/** 列表项内边距总和(像素) */
const ITEM_PADDING = 16
/** 上下缓冲区域的项目数量 */
const BUFFER_COUNT = 10
/** 滚动防抖时间(毫秒) */
const SCROLL_DEBOUNCE_TIME = 16
// 计算列表项实际总高度
const totalItemHeight = computed(() =>
props.config.itemHeight + props.config.itemPadding
ITEM_HEIGHT + ITEM_PADDING
)
// 响应式状态管理
@@ -46,10 +55,10 @@ const visibleCount = computed(() =>
// 计算当前需要渲染的数据
const visibleData = computed(() => {
const visibleStart = Math.max(0, startIndex.value - props.config.bufferCount)
const visibleStart = Math.max(0, startIndex.value - BUFFER_COUNT)
const visibleEnd = Math.min(
props.data.length,
startIndex.value + visibleCount.value + props.config.bufferCount
startIndex.value + visibleCount.value + BUFFER_COUNT
)
return props.data.slice(visibleStart, visibleEnd).map((item, index) => ({
@@ -60,7 +69,7 @@ const visibleData = computed(() => {
// 计算列表偏移量
const offsetY = computed(() =>
Math.max(0, (startIndex.value - props.config.bufferCount) * totalItemHeight.value)
Math.max(0, (startIndex.value - BUFFER_COUNT) * totalItemHeight.value)
)
// 计算虚拟列表总高度
@@ -117,7 +126,7 @@ function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): (..
/**
* 处理滚动事件(已防抖)
* 根据滚动位置更新可视区的起始索引
* 根据滚动位置更新可视区<EFBFBD><EFBFBD>的起始索引
*/
const handleScroll = debounce(() => {
if (!containerRef.value) return
@@ -127,7 +136,7 @@ const handleScroll = debounce(() => {
if (newStartIndex !== startIndex.value) {
startIndex.value = newStartIndex
}
}, props.config.scrollDebounceTime)
}, SCROLL_DEBOUNCE_TIME)
/** 鼠标悬停禁用状态 */
const disableHover = ref<boolean>(false)
@@ -293,7 +302,7 @@ onMounted(() => {
// 初始化容器高度
updateContainerHeight()
// 添加全局事监听
// 添加全局事<EFBFBD><EFBFBD>监听
window.addEventListener('resize', updateContainerHeight)
window.addEventListener('keydown', handleKeyDown)
})
@@ -341,7 +350,7 @@ onBeforeUnmount(() => {
:key="item.index"
class="list-item"
:class="{ 'selected': selectedIndex === item.index }"
:style="{ height: `${config.itemHeight}px` }"
:style="{ height: `${ITEM_HEIGHT}px` }"
@mouseenter="handleMouseEnter(item.index)"
@click="handleClick(item)"
@contextmenu="handleContextMenu($event, item)"