解決element-ui el-select資料過大方案

北漂生活發表於2024-03-27

一、背景

專案中需要用到el-select選擇醫院,全國醫院資料量非常大,透過API讀取資料頁面直接卡死。

二、解決方案

1、元件:el-select + vue虛擬滾動(vue-virtual-scroll-list)

2、安裝:npm install vue-virtual-scroll-list --save

3、參考:

    NPM地址:https://www.npmjs.com/package/vue-virtual-scroll-list

    官網地址:https://tangbc.github.io/vue-virtual-scroll-list/#/

三:參考程式碼

###create.vue

<template> <div> <el-form ref="dataForm" :model="form" :rules="rules" label-width="0px"> <el-descriptions :column="3" border> <el-descriptions-item labelStyle="width: 13%" contentStyle="width: 20%"> <template slot="label"><span class="red">*</span> 醫院</template> <el-form-item label="" prop="hospital_id"> <el-select @change="changeValue" remote :remote-method="getListHospital" :loading="loading" v-model="form.hospital_id" :placeholder="'請輸入醫院'" size="small" filterable clearable> <virtual-list style="height: 150px; overflow-y: auto;" :data-key="'id'" :data-sources="hospitalData" :data-component="itemComponent" /> </el-select> </el-form-item> </el-descriptions-item> </el-descriptions> </el-form> </div> </template> <script> import {allHospital, listHospital} from "@/api/system/hospital"; import Item from "./item"; import VirtualList from 'vue-virtual-scroll-list' export default { props: ["rowData", "dialogStatus"], components: { VirtualList, }, data() { return { itemComponent: Item, hospitalData: [], loading: false, }; }, created() { if (this.dialogStatus === "update" || this.dialogStatus === "detail") { this.form = {...this.rowData}; this.getAllHospital(); } }, methods: { changeValue(id) { if (id) { let item = this.hospitalData.find(item => item.id === id); this.form.hospital_name = item.hospital } }, /** * 獲取醫院列表 */ getAllHospital() { if (this.form.hospital_id !== '') { let param = { id: this.form.hospital_id, field:"id,hospital" }; allHospital(param).then((res) => { if (res.code === 200) { this.hospitalData = res.data; } }); } }, getListHospital(query) { if (query !== '') { this.loading = true; setTimeout(() => { this.loading = false; let param = { hospital: query, pageSize: 100, field:"id,hospital" }; listHospital(param).then((res) => { if (res.code === 200) { this.hospitalData = res.data.data; } }); }, 200); } }, }, }; </script>



###item.vue
<template>
<el-option :label="source.hospital" :value="source.id"></el-option>
</template>

<script>
export default {
name: 'item-component',
props: {
index: { // index of current item
type: Number
},
source: { // here is: {uid: 'unique_1', text: 'abc'}
type: Object,
default() {
return {}
}
}
}
}
</script>

四:解決樣式

1、支援el-select一切屬性,利用select遠端搜尋,解決大資料查詢問題

相關文章