vue2实现虚拟滚动select下拉组件-上万条数据下拉支持过滤(样式仿el-select)
发布人:shili8
发布时间:2025-01-05 01:16
阅读次数:0
**Vue2 实现虚拟滚动Select下拉组件**
在实际项目中,经常会遇到需要渲染大量数据的场景,如下拉列表、表格等。在这些情况下,如果直接使用原生DOM进行渲染,可能会导致性能问题和页面卡顿。因此,我们可以使用虚拟滚动技术来优化性能。
在本文中,我们将实现一个支持过滤的虚拟滚动Select下拉组件,样式仿el-select。
**组件结构**
首先,我们需要定义组件的结构:
html<template>
<div class="virtual-scroll-select">
<!-- 滚动容器 -->
<div ref="scrollContainer" class="scroll-container">
<!-- 项列表 -->
<ul v-if="list.length >0" class="item-list">
<li v-for="(item, index) in list" :key="index" @click="handleItemClick(item)">
{{ item.label }}
</li>
</ul>
</div>
<!-- 输入框 -->
<input ref="input"
type="text"
v-model="filterValue"
placeholder="请输入内容..."
@input="handleInput"
@focus="handleFocus"
@blur="handleBlur"
/>
</div>
</template>
**组件逻辑**
接下来,我们需要实现组件的逻辑:
javascriptexport default {
name: 'VirtualScrollSelect',
data() {
return {
list: [], // 项列表 filterValue: '', // 过滤值 scrollContainerHeight:0, // 滚动容器高度 itemSize:40, // 项大小 startIndex:0, // 开始索引 endIndex:10, // 结束索引 }
},
mounted() {
this.initList();
},
methods: {
initList() {
// 初始化项列表 this.list = [...Array(10000)].map((_, index) => ({
label: `项 ${index +1}`,
}));
},
handleInput(event) {
// 过滤值改变时更新列表 const filterValue = event.target.value;
this.filterValue = filterValue;
this.updateList(filterValue);
},
updateList(filterValue) {
// 更新列表 const list = this.list.filter((item) => item.label.includes(filterValue));
this.list = list;
this.updateScrollContainerHeight();
},
handleFocus() {
// 焦点时更新滚动容器高度 this.updateScrollContainerHeight();
},
updateScrollContainerHeight() {
// 更新滚动容器高度 const scrollContainer = this.$refs.scrollContainer;
const itemSize = this.itemSize;
const startIndex = this.startIndex;
const endIndex = this.endIndex;
const height = (endIndex - startIndex) * itemSize +10; // 加上边框和内边距 scrollContainer.style.height = `${height}px`;
},
handleItemClick(item) {
// 项点击时更新列表 this.list = [...Array(10000)].map((_, index) => ({
label: `项 ${index +1}`,
}));
this.updateList('');
},
}
}
**样式**
最后,我们需要定义组件的样式:
css.virtual-scroll-select {
position: relative;
}
.scroll-container {
overflow-y: auto;
padding:10px;
border:1px solid #ddd;
box-shadow:02px4px rgba(0,0,0,0.1);
}
.item-list {
list-style: none;
margin:0;
padding:0;
}
.item-list li {
padding:10px;
border-bottom:1px solid #ddd;
cursor: pointer;
}
.item-list li:hover {
background-color: #f5f5f5;
}
**总结**
在本文中,我们实现了一个支持过滤的虚拟滚动Select下拉组件,样式仿el-select。通过使用虚拟滚动技术和过滤功能,可以优化性能并提高用户体验。
当然,这只是一个基本示例,你可以根据实际需求进行扩展和修改。

