问题描述:当接口返回下拉数据量特别大的时候, 页面会卡顿, 下面采用下拉加载指定数据的方式来优化。
<template>
<el-select
v-model="value"
filterable
placeholder="Select"
v-focus="loadData(loadNumber)"
>
<el-option
v-for="item in options.slice(0, loadNumber)"
:key="item.employeeId"
:label="item.userName"
:value="item.employeeId"
/>
</el-select>
</template>
<script setup>
import { reactive, ref } from "vue";
const value = ref("");
const loadNumber = ref(10);
let options = reactive([]);
for (let i = 0; i < 2000; i++) {
options[i] = {
employeeId: i,
userName: `小${i}`,
};
}
const loadData = (n) => {
// elementui下拉超过7条才会出滚动条,如果初始不出滚动条无法触发loadData方法
return () => (loadNumber.value += 5); // 每次滚动到底部新增条数
};
const vFocus = {
mounted(el, binding) {
const SELECTWRAP_DOM = document.querySelector(
".el-select-dropdown .el-select-dropdown__wrap"
);
if (SELECTWRAP_DOM) {
SELECTWRAP_DOM.addEventListener("scroll", function () {
/**
* scrollHeight 获取元素内容高度
* scrollTop 获取或者设置元素的偏移值,
* clientHeight 读取元素的可见高度
* 如果元素滚动到底, 以下返回true, 没有返回false:
* *.scrollHeight - *.scrollTop === *.clientHeight;
*/
const condition =
SELECTWRAP_DOM.scrollHeight - SELECTWRAP_DOM.scrollTop <=
SELECTWRAP_DOM.clientHeight;
if (condition) binding.value();
});
}
},
};
</script>