优化el-select选项太多,界面卡顿的问题

67 阅读1分钟

优化el-select选项太多,界面卡顿的问题

使用组件完成

  1. 首先安装 npm install vue-virtual-scroll-list
  2. 新建组件ItemOption
<template>
  <el-option :key="index" :label="source[label]" :value="source[value]" @click="handleClick"></el-option>
</template>

<script>
export default {
  name: 'item-component',
  props: {
    index: { // 每一行的索引
      type: Number
    },
    source: { // 每一行的内容
      type: Object,
      default () {
        return {}
      }
    },
    label: { // 要显示的名称
      type: String
    },
    value: { // 绑定的值
      type: String
    },
  },
  methods: {
    handleClick() {
    }
  },
}
</script>
  1. 新建组件SelectItem
<template>
  <el-select v-model="data" clearable placeholder="请选择" multiple filterable @change="updateValue">
    <virtual-list
      style="height: 100%; overflow-y: auto; padding-right: 16px"
      :data-key="'id'"
      :data-sources="options"
      :data-component="itemComponent"
      :keeps="100"
      :extra-props="{
              label: 'label',
              value: 'label'
            }"
    />
  </el-select>
</template>

<script>
import Item from "@/components/VirtualScroll/ItemOption.vue";

export default {
  props: {
    value: {
      type: Array,
      default: () => ([])
    },
    options: {
      type: Array,
      default: () => ([])
    },
  },
  data() {
    return {
      data: this.value,
      itemComponent: Item,
    }
  },
  watch: {
    value(newVal) {
      // 监听父组件传递的数据变化
      this.data = newVal;
    },
  },
  methods: {
    updateValue() {
      this.$emit('input', this.data);
    }
  },
}
</script>

<style scoped lang="scss">

</style>
  1. 在界面引入组件 import SelectItem from "@/components/VirtualScroll/SelectItem.vue";
  2. 组件使用
<select-item v-model="hlt"
             :options="options"
             @input="updateParentValue($event, 'hlt')"
></select-item>