当前位置: 首页 > news >正文

virtualList 封装使用 虚拟列表 列表优化

虚拟列表 列表优化

  • virtualList 组件封装

virtualList 组件封装

本虚拟列表 要求一次性加载完所有数据 不适合分页
新建一个select.vue 组件页面

<template><div>	<el-select transfer="true"   :popper-append-to-body="true"popper-class="virtualselect"class="virtual-select-custom-style":value="defaultValue"filterable:filter-method="filterMethod"default-first-optionclearable:placeholder="placeholderParams":multiple="isMultiple":allow-create="allowCreate"@visible-change="visibleChange"v-on="$listeners"@clear="clearChange"><virtual-listref="virtualList"class="virtualselect-list":data-key="value":data-sources="selectArr":data-component="itemComponent":keeps="keepsParams":extra-props="{label: label,value: value,labelTwo:labelTwo,isRight: isRight,isConcat: isConcat,isConcatShowText:isConcatShowText,concatSymbol: concatSymbol}"></virtual-list></el-select></div>
</template>
<script>import {validatenull} from '@/utils/validate.js'import virtualList from 'vue-virtual-scroll-list'import ElOptionNode from './el-option-node'export default {components: {'virtual-list': virtualList},model: {prop: 'bindValue',event: 'change'},props: {// 数组list: {type: Array,default() {return []}},// 显示名称1label: {type: String,default: ''},// 显示名称2 labelTwo: {type: String,default: ''},// 标识value: {type: String,default: ''},// 是否拼接label | valueisConcat: {type: Boolean,default: false},isConcatShowText:{type: Boolean,default: false},// 拼接label、value符号concatSymbol: {type: String,default: ' | '},// 显示右边isRight: {type: Boolean,default: false},// 加载条数keepsParams: {type: Number,default: 10},// 绑定的默认值bindValue: {type: [String, Array,Number],default() {if (typeof this.bindValue === 'string') return ''return []}},// 是否多选isMultiple: {type: Boolean,default: false},placeholderParams: {type: String,default: '请选择'},// 是否允许创建条目allowCreate: {type: Boolean,default: true}},data() {return {itemComponent: ElOptionNode,selectArr: [],defaultValue: null // 绑定的默认值}},watch: {'list'() {this.init()},bindValue: {handler(val, oldVal) {this.defaultValue = this.bindValueif (validatenull(val)) this.clearChange()this.init()},immediate: false,deep: true}},mounted() {this.defaultValue = this.bindValuethis.init()},methods: {init() {if (!this.defaultValue || this.defaultValue?.length === 0) {this.selectArr = this.list} else {// 回显问题// 由于只渲染固定keepsParams(10)条数据,当默认数据处于10条之外,在回显的时候会显示异常// 解决方法:遍历所有数据,将对应回显的那一条数据放在第一条即可this.selectArr = JSON.parse(JSON.stringify(this.list))if (typeof this.defaultValue === 'string' && !this.isMultiple) {let obj = {}if (this.allowCreate) {const arr = this.selectArr.filter(val => {return val[this.value] === this.defaultValue})if (arr.length === 0) {const item = {}// item[this.value] = `Create-${this.defaultValue}`item[this.value] = this.defaultValueitem[this.label] = this.defaultValueitem.allowCreate = truethis.selectArr.push(item)this.$emit('selChange', item)} else {this.$emit('selChange', arr[0])}}// 单选for (let i = 0; i < this.selectArr.length; i++) {const element = this.selectArr[i]// if (element[this.value]?.toLowerCase() === this.defaultValue?.toLowerCase()) {if (element[this.value] === this.defaultValue) {obj = elementthis.selectArr?.splice(i, 1)break}}this.selectArr?.unshift(obj)} else if (this.isMultiple) {if (this.allowCreate) {this.defaultValue.map(v => {const arr = this.selectArr.filter(val => {return val[this.value] === v})if (arr?.length === 0) {const item = {}// item[this.value] = `Create-${v}`item[this.value] = vitem[this.label] = vitem.allowCreate = truethis.selectArr.push(item)this.$emit('selChange', item)} else {this.$emit('selChange', arr[0])}})}// 多选for (let i = 0; i < this.selectArr.length; i++) {const element = this.selectArr[i]this.defaultValue?.map(val => {// if (element[this.value]?.toLowerCase() === val?.toLowerCase()) {if (element[this.value]=== val) {obj = elementthis.selectArr?.splice(i, 1)this.selectArr?.unshift(obj)}})}}}},// 搜索filterMethod(query) {if (!validatenull(query?.trim())) {this.$refs.virtualList.scrollToIndex(0) // 滚动到顶部setTimeout(() => {this.selectArr = this.list.filter(item => {return this.isRight || this.isConcat? (item[this.label].trim()?.toLowerCase()?.indexOf(query?.trim()?.toLowerCase()) > -1 || (item[this.labelTwo]+'')?.toLowerCase()?.indexOf(query?.trim()?.toLowerCase()) > -1): item[this.label]?.toLowerCase()?.indexOf(query?.trim()?.toLowerCase()) > -1// return this.isRight || this.isConcat? (item[this.label].trim().indexOf(query.trim()) > -1 || (item[this.value]+'').trim().indexOf(query.trim()) > -1)//   : item[this.label].indexOf(query.trim()) > -1})}, 100)} else {setTimeout(() => {this.init()}, 100)}},visibleChange(bool) {if (!bool) {this.$refs.virtualList.reset()this.init()}},clearChange() {if (typeof this.defaultValue === 'string') {this.defaultValue = ''} else if (this.isMultiple) {this.defaultValue = []}this.visibleChange(false)}}}
</script>
<style lang="scss" scoped>.virtual-select-custom-style{width:100% !important;}
.virtual-select-custom-style ::v-deep .el-select-dropdown__item {// 设置最大宽度,超出省略号,鼠标悬浮显示// options 需写 :title="source[label]"min-width: 300px;max-width: 480px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;
}
.virtualselect {// 设置最大高度&-list {max-height:245px;overflow-y:auto;}
}
::-webkit-scrollbar {width: 6px;height: 6px;background-color: transparent;cursor: pointer;margin-right: 5px;
}
::-webkit-scrollbar-thumb {background-color: rgba(144,147,153,.3) !important;border-radius: 3px !important;
}
::-webkit-scrollbar-thumb:hover{background-color: rgba(144,147,153,.5) !important;
}
::-webkit-scrollbar-track {background-color: transparent !important;border-radius: 3px !important;-webkit-box-shadow: none !important;
}
::v-deep  .el-select__tags {flex-wrap: unset;overflow: auto;
}
</style>

新建一个组件 el-option-node.vue

<template><el-option:key="label+value":label="concatString2(source[label], source[labelTwo])":value="source[value]":disabled="source.disabled":title="concatString2(source[label], source[labelTwo])"><span >{{ concatString(source[label], source[labelTwo]) }}</span><spanv-if="isRight"style="float:right;color:#939393">{{ source[value] }}</span></el-option>
</template>
<script>export default {name: 'ItemComponent',props: {// 每一行的索引index: {type: Number,default: 0},// 每一行的内容source: {type: Object,default() {return {}}},// 需要显示的名称label: {type: String,default: ''},// 需要显示的名称labelTwo: {type: String,default: ''},// 绑定的值value: {type: String,default: ''},// 是否拼接label | valueisConcat: {type: Boolean,default: false},isConcatShowText:{type: Boolean,default: false},// 拼接label、value符号concatSymbol: {type: String,default: ' | '},// 右侧是否显示绑定的值isRight: {type: Boolean,default() {return false}}},methods: {//选择后 只显示label//张三concatString(a, b) {a = a || ''b = b || ''if (this.isConcat) {// return a + ((a && b) ? ' | ' : '') + breturn a + ((a && b) ? this.concatSymbol : '') + b}return a},//选择下拉展示时 可以展示label和labelTwo//123||张三concatString2(a, b) {a = a || ''b = b || ''if (this.isConcat) {// return a + ((a && b) ? ' | ' : '') + bif(this.isConcatShowText==true){return a + ((a && b) ? this.concatSymbol : '') + b}else{return a}}return a}}}
</script>

组件建议完成后 在页面使用:

list:数据 [{name:‘张三’,code:‘098’},{}] label:要显示的字段1 labelTwo:要显示的字段2
concat-symbol:拼接符号 is-concat是否拼接 is-multiple:是否多选 allowCreate是否可以创建目录 @change 事件 keeps-params数据多少条

<template><div><virtual-select v-model="item.contractGodsId":list="goodsList" label="name" labelTwo="code" value="id" :placeholder-params="'请选择产品'":keeps-params="10" :is-concat="true" :isConcatShowText="false":concat-symbol="' || '" :is-multiple="false" :allowCreate="false"@change="goodsChange($event,$index)" /></div>
</template>引入组件import VirtualSelect from '@/views/components/virtualList/select'export default {components: {VirtualSelect},}

如果label和labelTwo都填写了,显示效果如下

请添加图片描述

本虚拟列表 要求一次性加载完所有数据 不适合分页

相关文章:

  • 15.1 自动化黑屏监测系统
  • Windows power shell for循环
  • Vue2系列 — 渲染函数 (render + createElement)
  • 卷积神经网络(Inception V3)识别手语
  • 关于AssetBundle禁用TypeTree之后的一些可序列化的问题
  • ArgoWorkflow教程(一)---DevOps 另一选择?云原生 CICD: ArgoWorkflow 初体验
  • 音频采集的相关基础知识
  • 【数据结构初阶(4)】栈的基本操作实现
  • 【DevOps】Git 图文详解(七):标签管理
  • 基于法医调查算法优化概率神经网络PNN的分类预测 - 附代码
  • 基于Springboot+Vue选课系统
  • PTA 海盗分赃
  • Ubuntu 1.84.2Visual Studio Code 下载配置与vscode查看内存Hex Editor插件,简单易懂
  • 376.摆动序列
  • 【完美世界】叶倾仙强势登场,孔雀神主VS护道人,石昊重逢清漪
  • Java 内存分配及垃圾回收机制初探
  • Java 最常见的 200+ 面试题:面试必备
  • Java面向对象及其三大特征
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • vue-cli在webpack的配置文件探究
  • 从输入URL到页面加载发生了什么
  • 基于HAProxy的高性能缓存服务器nuster
  • 那些被忽略的 JavaScript 数组方法细节
  • 配置 PM2 实现代码自动发布
  • 通过git安装npm私有模块
  • # C++之functional库用法整理
  • #传输# #传输数据判断#
  • #我与Java虚拟机的故事#连载07:我放弃了对JVM的进一步学习
  • (附源码)springboot社区居家养老互助服务管理平台 毕业设计 062027
  • (附源码)ssm基于web技术的医务志愿者管理系统 毕业设计 100910
  • (详细文档!)javaswing图书管理系统+mysql数据库
  • (转)德国人的记事本
  • (转载)虚函数剖析
  • .apk文件,IIS不支持下载解决
  • .config、Kconfig、***_defconfig之间的关系和工作原理
  • .desktop 桌面快捷_Linux桌面环境那么多,这几款优秀的任你选
  • .NET 2.0中新增的一些TryGet,TryParse等方法
  • .Net core 6.0 升8.0
  • .NET 药厂业务系统 CPU爆高分析
  • .Net 中的反射(动态创建类型实例) - Part.4(转自http://www.tracefact.net/CLR-and-Framework/Reflection-Part4.aspx)...
  • .NetCore部署微服务(二)
  • .NET性能优化(文摘)
  • @ 代码随想录算法训练营第8周(C语言)|Day53(动态规划)
  • @Autowired 和 @Resource 区别的补充说明与示例
  • @RequestParam,@RequestBody和@PathVariable 区别
  • @Transactional 详解
  • [ 数据结构 - C++] AVL树原理及实现
  • [1] 平面(Plane)图形的生成算法
  • [2024-06]-[大模型]-[Ollama]- WebUI
  • [APUE]进程关系(下)
  • [bzoj1901]: Zju2112 Dynamic Rankings
  • [C#]使用C#部署yolov8的目标检测tensorrt模型
  • [C][栈帧]详细讲解
  • [C++]类和对象【下】
  • [Contest20180313]灵大会议