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

文章介绍了如何在Vue中封装一个虚拟列表组件,用于el-select中的selecttransfer,强调了当数据量大不适合分页加载的情况,并提供了组件代码示例和相关配置选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

虚拟列表 列表优化

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都填写了,显示效果如下

请添加图片描述

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

### 集成 `vue-virtual-scroll-list` 到 Element UI 的 `el-table` 为了提高大型表格的数据加载性能,可以在 `el-table` 组件中引入虚拟滚动技术。通过使用 `vue-virtual-scroller` 或者类似的库来优化渲染过程。 #### 安装依赖 安装所需的包: ```bash npm install vue-virtual-scroller # 或者 yarn add vue-virtual-scroller ``` #### 创建自定义组件 创建一个新的 Vue 组件用于封装带有虚拟滚动功能的表格视图: ```html <template> <div class="virtualized-table"> <!-- 使用 VirtualList 替代默认的 el-table --> <RecycleScroller :items="dataSource" :item-size="38" key-field="id" v-bind="$attrs" ref="scrollerRef" @scroll="handleScroll" > <template v-slot="{ item }"> <el-row type="flex" align="middle" justify="space-between"> <el-col>{{ item.name }}</el-col> <el-col>{{ item.value }}</el-col> </el-row> </template> </RecycleScroller> </div> </template> <script setup lang="ts"> import { defineProps, computed } from 'vue'; import { RecycleScroller } from 'vue-virtual-scroller'; const props = defineProps({ dataSource: Array, }); // 计算属性或其他逻辑... function handleScroll(event){ console.log('Table Scrolled', event); } </script> <style scoped> .virtualized-table { max-height: 400px; overflow-y: auto; } /* 覆盖原有样式 */ .el-scrollbar__wrap{ margin-bottom: unset !important; } </style> ``` 此代码片段展示了如何将 `RecycleScroller` 和 `el-table` 结合起来工作[^1]。注意这里替换了标准 `<el-table>` 标签为来自 `vue-virtual-scroller` 库中的 `<RecycleScroller>`, 并调整了一些内部结构以适应新的布局方式。 #### 设置样式避免双重滚动条问题 为了避免出现双层滚动条的情况,在 CSS 文件里添加特定的选择器覆盖默认行为并移除不必要的部分[^2]: ```css .virtualSelect .el-scrollbar .el-scrollbar__bar.is-vertical { display: none; } ``` 同时确保给容器指定了固定的 `max-height` 属性以及开启垂直方向上的溢出处理(`overflow-y:auto`)。 #### 关键配置项说明 - **data-key**: 指定每一行记录唯一的标识字段名称。 - **data-sources**: 提供整个数据集作为源列表传递给子组件。 - **keeps**: 控制每次可见区域内的项目数量,默认值可以根据实际需求设定。 - **extra-props**: 可选参数允许向模板内嵌套的内容注入额外变量或方法。 以上就是关于在 `element-ui` 表格中应用虚拟滚动效果的主要步骤和技术要点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值