標(biāo)簽: Vue element-ui
原因:下拉框數(shù)據(jù)過(guò)多,若渲染全部數(shù)據(jù),會(huì)導(dǎo)致 DOM 數(shù)量太多,操作卡頓。
解決辦法:將獲取的數(shù)據(jù)(allList)和渲染數(shù)據(jù)(list)分離開(kāi),限制渲染數(shù)組的長(zhǎng)度。
<template>
<el-select v-model="value" filterable :filter-method="filterList" placeholder="請(qǐng)選擇">
<el-option
v-for="item in allList"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
// 渲染列表,限制在20個(gè)以內(nèi)
list: [],
// 請(qǐng)求獲取的列表,數(shù)據(jù)量過(guò)大時(shí)不能直接渲染,會(huì)卡頓
allList: [
{
value: "選項(xiàng)1",
label: "黃金糕"
},
{
value: "選項(xiàng)2",
label: "雙皮奶"
},
{
value: "選項(xiàng)3",
label: "蚵仔煎"
},
{
value: "選項(xiàng)4",
label: "龍須面"
},
{
value: "選項(xiàng)5",
label: "北京烤鴨"
}
],
value: ""
};
},
created() {
// 模擬某些情況,需要設(shè)置默認(rèn)的下拉選項(xiàng),防止默認(rèn)選中值顯示不正常(例如:不顯示label,而顯示value)
this.list = [{
value: "選項(xiàng)4",
label: "龍須面"
},
{
value: "選項(xiàng)5",
label: "北京烤鴨"
}]
},
methods: {
filterList(query = "") {
let arr = this.allList.filter(item => {
return item.label.includes(query) || item.value.includes(query);
});
if (arr.length > 20) {
this.list = arr.slice(0, 20);
} else {
this.list = arr;
}
}
}
};
</script>