解决el-select下拉列表数据量过大卡顿问题

效果:

在这里插入图片描述
在这里插入图片描述

说明

使用虚拟列表,解决卡顿问题,vue-virtual-scroll-list (github地址)

代码

1、使用组件页面 index.vue

<template>
  <div style="margin: 20px">
    <div>---单选---</div>
    <VirtualSelectList
      :width="300"
      style="margin: 20px"
      size="small"
      placeholder="单选"
      clearfix
      :propsDefine="propsDefine"
      :dataList="projectList"
      :keeps="30"
      :estimateSize="32"
      :virtualClickItemCall="virtualClickItemCall"
    ></VirtualSelectList>
    <div>------多选------</div>
    <virtualSelectList
      style="margin: 20px"
      multiple
      clearable
      :selectIds="selectIds"
      :width="420"
      size="small"
      placeholder="多选"
      clearfix
      :propsDefine="propsDefine"
      :dataList="projectList"
      :keeps="30"
      :estimateSize="32"
      @clearAll="clearAll"
      :virtualClickItemCall="virtualMultipleClickItemCall"
    ></virtualSelectList>
  </div>
</template>

<script>
import VirtualSelectList from "./components/VirtualSelectList.vue";
export default {
  data() {
    return {
      propsDefine: { value: "id", label: "name" },
      projectList: [],
      //多选相关
      selectIds: [],
    };
  },
  components: {
    VirtualSelectList,
  },
  created() {
    for (let index = 0; index < 10000; index++) {
      let obj = {
        id: index,
        name: `namename-------${index}`,
      };
      this.projectList.push(obj);
    }
  },
  methods: {
    // 单选点击回调
    virtualClickItemCall(item) {
      console.log(item);
      this.$nextTick(() => {
        // 触发修改后续事件
      });
    },
    //多选 清空所已选项
    clearAll() {
      this.selectIds = [];
    },
    //多选点击回调
    virtualMultipleClickItemCall(item) {
      console.log(item, "item");
      let selectIds = this.selectIds;
      const index = selectIds.indexOf(item[this.propsDefine.value]);
      if (index === -1) {
        selectIds.push(item[this.propsDefine.value]);
      } else {
        selectIds.splice(index, 1);
      }
      this.selectIds = selectIds;
      this.$nextTick(() => {
        // 触发修改后续事件
      });
    },
  },
};
</script>

2、下拉虚拟列表组件 VirtualSelectList.vue

<template>
    <el-popover
        v-model="visibleVirtualList"
        popper-class="select-virtual-list-popover"
        trigger="click"
        placement="bottom-start"
        :width="width">
        <virtual-list v-if="visibleVirtualList && virtualDataList.length > 0"
                      ref="virtualListRef"
                      class="virtual-list hx-scroll"
                      :extra-props="{ curId,selectIds,multiple,propsDefine}"
                      :data-key="propsDefine.value"
                      :keeps="keeps"
                      :data-sources="virtualDataList"
                      :data-component="itemComponent"
                      :estimate-size="estimateSize"
                      :item-class="'list-item-custom-class'"
        ></virtual-list>
        <div v-else class="empty-list">无匹配数据</div>
        <template slot="reference">
            <!--            多选-->
            <div v-if="multiple" class="multiple-select-box" :style="`width:${width}px;`">
                <div v-if="multipleText" class="select-text" :style="`width:${width / 2}px;`">
                    <el-tooltip class="text-conent" :content="multipleText">
                        <span class="ellipsis">{{ multipleText }}</span>
                    </el-tooltip>
                    <i class="el-icon-close" @click="clearItem"></i>
                </div>
                <span v-if="selectIds.length > 1" class="select-num">+{{ selectIds.length - 1 }}</span>
                <el-input
                    class="filter-el-input"
                    v-if="filterable"
                    v-model="filterValue"
                    :size="size"
                    :placeholder="placeholder"
                    :clearable="!!clearfix"
                    @input="handleInput"
                ></el-input>
                <span class="select-suffix" :class="{'show-close-all':selectIds.length}">
                    <span class="arrow-box">
                        <i v-if="visibleVirtualList" class="el-icon-arrow-up"></i>
                        <i v-else class="el-icon-arrow-down"></i>
                    </span>
                    <span v-if="selectIds.length" class="clear-box" @click="clearAll">
                        <i class="el-icon-close"></i>
                    </span>
                </span>
            </div>
            <!--            单选-->
            <div v-else class="virtual-select-input" :style="`width:${width}px;`">
                <el-input
                    v-model="curValue"
                    :style="{width: '100%'}"
                    :size="size"
                    :placeholder="placeholder"
                    :clearable="!!clearfix"
                    @input="handleInput"
                ></el-input>
            </div>
        </template>
    </el-popover>
</template>

<script>
import VirtualList from 'vue-virtual-scroll-list';
import VirtualItem from './VirtualItem.vue'

export default {
    name: 'SelectVirtualList',
    props: {
        propsDefine: {
            type: Object,
            default: () => {
                return {
                    value: 'value',
                    label: 'label',

                }
            }
        },
        width: {
            type: Number,
            default: 250
        },
        size: {
            type: String,
            default: "small"
        },
        placeholder: {
            type: String,
            default: "请选择"
        },
        dataList: {
            type: Array,
            default: () => {
                return [];
            }
        },
        // 虚拟列表在真实 dom 中保持渲染的项目数量
        keeps: {
            type: Number,
            default: 30
        },
        // 每个项目的估计大小,如果更接近平均大小,则滚动条长度看起来更准确。 建议分配自己计算的平均值。
        estimateSize: {
            type: Number,
            default: 32
        },
        //过滤输入框是否可清空
        clearfix: {
            type: Boolean,
            default: true,
        },
        //多选模式 是否可以清空已选
        clearable: {
            type: Boolean,
            default: true,
        },
        filterable: {
            type: Boolean,
            default: true,
        },
        //是否多选
        multiple: {
            type: Boolean,
            default: false,
        },
        selectIds: {
            type: Array,
            default: () => {
                return [];
            }
        },
        // input输入触发方法
        virtualInputCall: Function,
        // 点击每个项目触发方法
        virtualClickItemCall: Function
    },
    components: {
        VirtualList
    },
    watch: {
        visibleVirtualList(n) {
            if (n) {
                // 当展示虚拟列表时,需要定位到选择的位置
                this.$nextTick(() => {
                    let temp = this.curIndex ? this.curIndex : 0;
                    if (this.multiple && this.selectIds.length) {
                        const value = this.propsDefine.value
                        const targetIndex = this.virtualDataList.findIndex(el => this.selectIds.includes(el[value]))
                        temp = targetIndex !== -1 ? targetIndex : 0
                    }
                    // 方法一:手动设置滚动位置到指定索引。
                    this.$refs.virtualListRef && this.$refs.virtualListRef.scrollToIndex(temp - 1);
                    // 方法二:手动将滚动位置设置为指定的偏移量。
                    // this.$refs.virtualListRef.scrollToOffset(this.estimateSize * (temp - 1));
                })
            }
        },
        dataList: {
            handler(val, oldV) {
                console.time('1111')
                if (val && val.length > 0) this.virtualDataList = [...val];
                console.timeEnd('1111')
            },
            immediate:true,
        },
    },
    data() {
        return {
            curId: "", // 当前选择的 id
            curValue: "", // 当前选择的值
            curIndex: null, // 当前选择的索引
            visibleVirtualList: false, // 是否显示虚拟列表
            itemComponent: VirtualItem, // 由 vue 创建/声明的渲染项组件,它将使用 data-sources 中的数据对象作为渲染道具并命名为:source。
            virtualDataList: [],
            filterValue: '',
        };
    },
    computed: {
        multipleText() {
            let text = ''
            if (this.dataList.length && this.selectIds.length) {
                let {value, label} = this.propsDefine;
                const firstItem = this.dataList.find(el => el[value] === this.selectIds[0])
                if (firstItem) {
                    text = firstItem[label]
                }
            }
            return text
        },
    },
    created() {
        // 监听点击子组件
        this.$on('clickVirtualItem', (item) => {
            console.log("item--->", item)
            let {value, label} = this.propsDefine;
            this.curId = item[value];
            this.curValue = item[label];
            this.curIndex = this.dataList.findIndex(row => row[value] == this.curId);
            if (!this.multiple) {
                this.visibleVirtualList = false;
            }
            this.virtualClickItemCall && this.virtualClickItemCall(item);
        })
    },

    methods: {
        // 输入框改变
        handleInput(val) {
            console.log("val--->", val);
            if (!this.multiple) {
                if (val === undefined || val === '') {
                    this.virtualClickItemCall && this.virtualClickItemCall('');
                } else {
                    this.curId = "";
                    this.curIndex = null;
                }
            }
            if (this.virtualInputCall) {
                this.virtualInputCall && this.virtualInputCall(val);
            } else {
                let {label} = this.propsDefine;
                this.virtualDataList = this.dataList.filter(i => i[label].indexOf(val) > -1);
            }
        },
        //多选模式下 点击去掉当前已选项
        clearItem() {
            if (this.multiple && this.selectIds.length) {
                const item = this.dataList.find(el => el[this.propsDefine.value] === this.selectIds[0])
                if (item) {
                    this.virtualClickItemCall && this.virtualClickItemCall(item);
                }
            }
        },
        clearAll() {
            this.$emit('clearAll')
        },
    }
};
</script>

<style lang='scss'>
.el-popover.el-popper.select-virtual-list-popover {
    //height: 300px;
    padding: 0;
    border: 1px solid #E4E7ED;
    border-radius: 4px;
    background-color: #FFFFFF;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-sizing: border-box;

    .virtual-list {
        max-height: 286px;
        min-height: 32px;
        width: 100%;
        height: 100%;
        padding: 10px 0;
        overflow-y: auto;
    }

    .empty-list {
        padding: 10px 0;
        margin: 0;
        text-align: center;
        color: #999;
        font-size: 14px;
    }
}

.multiple-select-box {
    display: flex;
    align-items: center;
    background-color: #e8ebf4;
    border-radius: 4px;
    height: 32px;
    padding: 0 20px 0 10px;
    position: relative;

    .select-text {
        display: flex;
        align-items: center;
        background-color: #f4f4f5;
        border-color: #e9e9eb;
        color: #909399;
        padding: 0 8px;
        height: 24px;
        line-height: 22px;


        .text-conent {
            font-size: 12px;
            flex: 1;
            width: 0;
        }


        .el-icon-close {
            display: block;
            border-radius: 50%;
            text-align: center;
            font-size: 12px;
            height: 16px;
            width: 16px;
            line-height: 16px;
            vertical-align: middle;
            cursor: pointer;
            background-color: #C0C4CC;
            color: #909399;
        }
    }

    .filter-el-input {
        flex: 1;
        width: 0;
        //margin: 0 10px;

        .el-input__inner {
            height: 24px;
            line-height: 22px;
            background: none !important
        }
    }

    .select-num {
        margin: 0 6px;
        background-color: #f4f4f5;
        border-color: #e9e9eb;
        color: #909399;
        height: 24px;
        line-height: 24px;
        padding: 0 8px;
        border-radius: 4px;
    }

    .select-suffix {
        position: absolute;
        height: 100%;
        line-height: 1;
        display: flex;
        align-items: center;
        right: 5px;
        top: 0;
        text-align: center;

        .clear-box {
            display: none;
            cursor: pointer;
        }

        &.show-close-all:hover {
            .clear-box {
                display: inline-block;
            }

            .arrow-box {
                display: none;
            }
        }
    }
}

.virtual-select-input {
    height: 32px;
    position: relative;

    .el-icon-circle-close {
        position: absolute;
        right: 10px;
        line-height: 32px;
    }

    &:hover {
        .el-icon-circle-close {
            visibility: visible;
        }
    }

}

</style>
<style lang="scss" scoped>
::v-deep {
    .el-input--suffix .el-input__inner {
        padding-right: 30px;
    }

    .virtual-select-input .el-icon-circle-close {
        right: 0px;
    }
}

</style>

3、下拉虚拟列表展示子目组件VirtualItem.vue

<template>
    <div
        :class="['virtual-item', {'is-selected': multiple ? selectIds.indexOf(source[propsDefine.value]) !== -1 : curId === source[propsDefine.value]}]"
        @click="handleClick">
        <span>{{ source[propsDefine.label] }}</span>
    </div>
</template>

<script>
export default {
    name: 'VirtualItem',
    props: {
        propsDefine: {
            type: Object,
            default: () => {
                return {}
            }
        },
        curId: {
            type: [String, Number],
            default: ""
        },
        source: {
            type: Object,
            default() {
                return {}
            }
        },
        //是否多选
        multiple: {
            type: Boolean,
            default: false,
        },
        selectIds: {
            type: Array,
            default: () => {
                return [];
            }
        },
    },
    methods: {
        dispatch(componentName, eventName, ...rest) {
            let parent = this.$parent || this.$root;
            let name = parent.$options.name;
            while (parent && (!name || name !== componentName)) {
                parent = parent.$parent;
                if (parent) {
                    name = parent.$options.name;
                }
            }
            if (parent) {
                parent.$emit.apply(parent, [eventName].concat(rest));
            }
        },
        handleClick() {
            // 通知 SelectVirtualList 组件,点击了项目
            this.dispatch('SelectVirtualList', 'clickVirtualItem', this.source);
        }
    }
}
</script>

<style lang="scss" scoped>
.virtual-item {
    font-size: 14px;
    padding: 0 20px;
    position: relative;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #606266;
    height: 32px;
    line-height: 32px;
    box-sizing: border-box;
    cursor: pointer;

    &:hover {
        background-color: #F5F7FA;
    }

    &.is-selected {
        color: #970022;
        font-weight: bold;
    }
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值