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

news2024/9/23 11:15:33

虚拟列表 列表优化

  • 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-option
      clearable
      :placeholder="placeholderParams"
      :multiple="isMultiple"
      :allow-create="allowCreate"
      @visible-change="visibleChange"
      v-on="$listeners"
      @clear="clearChange"
    >
      <virtual-list
        ref="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 []
        }
      },
      // 显示名称1
      label: {
        type: String,
        default: ''
      },
	  // 显示名称2 
	  labelTwo: {
	    type: String,
	    default: ''
	  },
      // 标识
      value: {
        type: String,
        default: ''
      },
      // 是否拼接label | value
      isConcat: {
        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.bindValue
          if (validatenull(val)) this.clearChange()
          this.init()
        },
        immediate: false,
        deep: true
      }
    },
    mounted() {
      this.defaultValue = this.bindValue
      this.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.defaultValue
                item[this.label] = this.defaultValue
                item.allowCreate = true
                this.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 = element
                this.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] = v
                  item[this.label] = v
                  item.allowCreate = true
                  this.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 = element
                  this.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>
    <span
      v-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 | value
      isConcat: {
        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) ? ' | ' : '') + b
			return 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) ? ' | ' : '') + b
	  		  if(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都填写了,显示效果如下

请添加图片描述

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1244508.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android修行手册-超出父布局进行显示以及超出父布局实现点击

Unity3D特效百例案例项目实战源码Android-Unity实战问题汇总游戏脚本-辅助自动化Android控件全解手册再战Android系列Scratch编程案例软考全系列Unity3D学习专栏蓝桥系列ChatGPT和AIGC &#x1f449;关于作者 专注于Android/Unity和各种游戏开发技巧&#xff0c;以及各种资源分…

ubuntu下docker环境使用GPU配置

本文主要讲述整个命令流程&#xff0c;具体讲解请看官网nvidia-容器工具包和一篇总结得很详细的博文docker使用GPU总结 docker的版本必须安装19.0版本以上的&#xff0c;这里也只讲19.0版本以上的使用方法 首先设置一下网络信息 curl -fsSL https://nvidia.github.io/libnvi…

批量插入SQL 错误 [933] [42000]: ORA-00933: SQL 命令未正确结束

使用DBeaver向【oracle数据库】插入大量数据 INSERT INTO Student(name,sex,age,address,birthday) VALUES(Nike,男,18,北京,2000-01-01) ,(Nike,男,18,北京,2000-01-01) ,(Nike,女,18,北京,2000-01-01) ,(Nike,女,18,北京,2000-01-01) ,(Nike,男,18,北京,2000-01-01) ,(Nike…

Visio学习笔记

1. 常用素材 1.1 立方体&#xff1a;张量, tensor 操作路径&#xff1a;更多形状 ⇒ 常规 ⇒ 基本形状 自动配色 在选择【填充】后Visio会自动进行配色&#xff1b;

我劝烂了,这东西大学生早用早解脱

大学生看我&#xff0c;这个东西太太太香了啊&#xff01;&#xff01;&#xff01; 要写论文&#xff0c;写总结的都给我用起来 这东西能自动写文章&#xff0c;想写几篇就写几篇&#xff0c;篇篇不重复&#xff01;只要输入一个标题&#xff0c;马上就能生成一篇。真的贼香…

2023-11-23 LeetCode每日一题(HTML 实体解析器)

2023-11-23每日一题 一、题目编号 1410. HTML 实体解析器二、题目链接 点击跳转到题目位置 三、题目描述 「HTML 实体解析器」 是一种特殊的解析器&#xff0c;它将 HTML 代码作为输入&#xff0c;并用字符本身替换掉所有这些特殊的字符实体。 HTML 里这些特殊字符和它们…

视频去水印软件有哪些?分享四款好用去水印软件

对于从事自媒体的朋友们来说&#xff0c;保护自己的视频作品免受盗用至关重要。为了标识归属&#xff0c;我们通常会在视频上添加水印。然而&#xff0c;当我们在寻找素材并打算进行剪辑时&#xff0c;发现素材上的水印会严重干扰使用。在这种情况下&#xff0c;我们需要采取一…

【Linux】who命令使用

who who命令用于显示系统中有哪些使用者正在上面&#xff0c;显示的资料包含了使用者 ID、使用的终端机、从哪边连上来的、上线时间、呆滞时间、CPU 使用量、动作等等。 著者 由Joseph Arceneaux、David MacKenzie和Michael Stone撰写。 语法 who [选项] [文件|参数] who命…

第19章JAVA绘图

19.1JAVA绘图类 绘图是高级程序设计中非常重要的技术 19.1.1Graphics类 Graphics类是所有图形上下文的抽象基类&#xff0c;它允许应用程序在组件以及闭屏图片上进行绘制 Graphics类封装了JAVA支持的基本绘图操作所需的状态信息&#xff0c;主要包括颜色&#xff0c;字体&…

Doris-集群部署(四)

创建目录并拷贝编译后的文件 1&#xff09;创建目录并拷贝编译后的文件 mkdir /opt/module/apache-doris-0.15.0 cp -r /opt/software/apache-doris-0.15.0-incubating-src/output /opt/module/apache-doris-0.15.02&#xff09;修改可打开文件数&#xff08;每个节点&#x…

jenkins 参数构建

应用保存 [rootjenkins-node1 .ssh]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved i…

yolov3学习总结

目标检测算法 单阶段&#xff1a;不提取出候选框&#xff0c;直接将整个图像输入模型中&#xff0c;算法直接输出检测结果&#xff0c;端到端 yolo&#xff0c;ssd 端到端&#xff0c;输入图像到网络中&#xff0c;然后从网络中输出图像 二阶段&#xff1a;先从图像中提取出…

探讨工业元宇宙和数字孪生的关系

就在各类技术专家还在试图设想元宇宙虚拟世界将为企业和消费者带来什么时&#xff0c;工业元宇宙虚拟世界已经在改变人们设计、制造以及与各行业物理实体互动的方式。尽管元宇宙的定义比比皆是&#xff0c;工业元宇宙将如何发展还有待观察&#xff0c;但数字孪生越来越多地被视…

面试cast:reinterpret_cast/const_cast/static_cast/dynamic_cast

目录 1. cast 2. reinterpret_cast 3. const_cast 3.1 加上const的情况 3.2 去掉const的情况 4. static_cast 4.1 基本类型之间的转换 4.2 void指针转换为任意基本类型的指针 4.3 子类和父类之间的转换 5. dynamic_cast 5.1 RTTI(Run-time Type Identification) 1.…

SQLY优化

insert优化 1.批量插入 手动事务提交 主键顺序插入&#xff0c;主键顺序插入性能高于乱序插入 2.大批量插入数据 如果一次性需要插入大批量数据&#xff0c;使用Insert语句插入性能较低&#xff0c;此时可以使用MYSQL数据库提供的load指令进行插入 主键优化 主键设计原则 …

计算机基础知识57

前后端数据传输的编码格式(contentType) # 我们只研究post请求方式的编码格式&#xff1a; get请求方式没有编码格式-- index?useranme&password get请求方式没有请求体&#xff0c;参数直接在url地址的后面拼接着 # 有哪些方式可以提交post请求&#xff1a;f…

SAP GOS与DMS简介

通常在项目实施过程中很多业务数据需要管理对应的系统外的附件&#xff0c; 制造业的BOM需要对应图纸&#xff0c;采购订单需要对应线下的采购合同&#xff0c;物料需要对应相应的参数文件等等&#xff0c;很多产品都会遇到业务数据和系统外相关资料的关联&#xff0c;有PDF的文…

2002-2020年341个地级市农业保险收入数据

2002-2020年341个地级市农业保险收入数据 1、时间&#xff1a;2002-2020年 2、范围&#xff1a;341个地级市 3、指标&#xff1a;农业保险收入 4、来源&#xff1a;整理自wind、保险年鉴 5、指标解释&#xff1a; 农业保险保费收入是指保险公司从农户或农业生产经营者那里…

聊一聊Linux动态链接和GOT、PLT

共享动态库是现代系统的一个重要组成部分&#xff0c;大家肯定都不陌生&#xff0c;但是通常对背后的一些细节上的实现机制了解得不够深入。当然&#xff0c;网上有很多关于这方面的文章。希望这篇文章能够以一种与其他文章不同的角度呈现&#xff0c;可以对你产生一点启发。 …

@Scheduled注解 定时任务讲解

用于在Java Spring框架中定时执行特定任务的注解 Scheduled&#xff0c;它能够指定方法在特定时间间隔或特定时间点执行。默认参数是cron&#xff0c;cron参数被用来定义一个Cron表达式&#xff0c;它代表了任务执行的时间规则 参数如下 Cron 这是是一种时间表达式&#xff…