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

虚拟列表 列表优化

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

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

相关推荐
27669582923 分钟前
京东e卡滑块 分析
java·javascript·python·node.js·go·滑块·京东
golitter.8 分钟前
Ajax和axios简单用法
前端·ajax·okhttp
PleaSure乐事17 分钟前
【Node.js】内置模块FileSystem的保姆级入门讲解
javascript·node.js·es6·filesystem
雷特IT28 分钟前
Uncaught TypeError: 0 is not a function的解决方法
前端·javascript
长路 ㅤ   1 小时前
vite学习教程02、vite+vue2配置环境变量
前端·vite·环境变量·跨环境配置
亚里士多没有德7751 小时前
强制删除了windows自带的edge浏览器,重装不了怎么办【已解决】
前端·edge
micro2010141 小时前
Microsoft Edge 离线安装包制作或获取方法和下载地址分享
前端·edge
.生产的驴1 小时前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
awonw1 小时前
[前端][easyui]easyui select 默认值
前端·javascript·easyui
老齐谈电商1 小时前
Electron桌面应用打包现有的vue项目
javascript·vue.js·electron