虛擬列表 列表優化
- 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都填寫了,顯示效果如下
本虛擬列表 要求一次性加載完所有數據 不適合分頁