当前位置: 首页 > news >正文

vue2中基于el-select封装一个懒加载下拉框

需求

当下拉选项的数据量过大时,后端接口是分页格式返回数据。

解决方案

自定义封装一个懒加载下拉组件,每次滚动到底部时自动获取下一页数据,这样可有效防止数据量过大时造成组件卡顿。

具体实现步骤

1、创建懒加载下拉选择组件

<template><el-selectv-model="innerValue":placeholder="placeholder":clearable="clearable":filterable="filterable":disabled="disabled"@change="handleChange"@visible-change="handleVisibleChange"@search="handleSearch"><el-optionv-for="item in options":key="item.value":label="item.label":value="item.value"></el-option><divv-if="loading"class="loading-more"style="text-align: center; padding: 10px 0;"><i class="el-icon-loading"></i></div><divv-if="!loading && hasMore"class="loading-more"style="text-align: center; padding: 10px 0;"><span>加载更多...</span></div></el-select>
</template><script>
export default {name: "LazyLoadSelect",props: {value: {type: [String, Number],default: "",},placeholder: {type: String,default: "请选择",},clearable: {type: Boolean,default: true,},filterable: {type: Boolean,default: true,},disabled: {type: Boolean,default: false,},fetchData: {type: Function,required: true,},},data() {return {innerValue: this.value,options: [],loading: false,hasMore: true,currentPage: 1,pageSize: 20,searchKeyword: "",handleScroll: null,};},watch: {value: {handler(val) {this.innerValue = val;},immediate: true,},},methods: {handleChange(value) {this.$emit("input", value);let label = this.options.find((item) => item.value === value).label;this.$emit("change", {value,label,});},async handleVisibleChange(visible) {if (visible) {// 下拉框打开时重置数据this.currentPage = 1;this.options = [];this.hasMore = true;await this.loadData();}},async handleSearch(query) {this.searchKeyword = query;this.currentPage = 1;this.options = [];this.hasMore = true;await this.loadData();},async loadData() {if (this.loading || !this.hasMore) return;this.loading = true;try {const res = await this.fetchData({current: this.currentPage,size: this.pageSize,condition: {nameRegex: this.searchKeyword,},});const newOptions = res.records && res.records.length > 0 ? res.records.map((item) => ({value: item.id,label: item.productName || item.areaName || item.salesmanName || item.agencyName || item.companyName || '',})) : [];this.options = [...this.options, ...newOptions];this.hasMore = newOptions.length === this.pageSize;this.currentPage++;} catch (error) {console.error("加载数据失败:", error);} finally {this.loading = false;}},},mounted() {// 监听滚动事件const selectDropdown = document.querySelector(".el-select-dropdown");if (selectDropdown) {this.handleScroll = () => {const { scrollTop, scrollHeight, clientHeight } = selectDropdown;// 当滚动到底部时加载更多数据if (scrollHeight - scrollTop - clientHeight < 50) {this.loadData();}};selectDropdown.addEventListener("scroll", this.handleScroll);}},beforeDestroy() {// 移除滚动事件监听const selectDropdown = document.querySelector(".el-select-dropdown");if (selectDropdown && this.handleScroll) {selectDropdown.removeEventListener("scroll", this.handleScroll);}},
};
</script><style lang="scss" scoped>
.loading-more {color: #909399;font-size: 12px;
}
</style>

2、使用懒加载下拉组件

// 引入懒加载下拉组件
import LazyLoadSelect from "@/components/lazyLoadSelect/index.vue";// 使用示例
<LazyLoadSelectv-model="searchForm.province":fetch-data="getArea()"placeholder="请选择":style="{ width: '200px' }"@change="handleProvinceChange"/>methods: {// 获取省份回调函数getArea() {return this.getAreaPage()},// 分页查询省份API接口调用getAreaPage async(params) {const res = await axios.post('/api/area/page', params)return res.data}
}              

写在最后

懒加载组件可以直接Copy进行使用,然后根据具体接口情况修改loadData方法中fetchData的请求参数和返回结果即可。

相关文章:

  • 从源码到实战:深度解析`rsync`增量同步机制与高级应用
  • 【HDFS入门】HDFS核心组件DataNode详解:角色职责、存储机制与健康管理
  • MyBatis-Plus 详解教程
  • 【专题刷题】双指针(一)
  • 静态站点生成
  • 解决USG5150防火墙web无法连接问题
  • 【AI论文】PixelFlow:基于流的像素空间生成模型
  • 【android bluetooth 协议分析 21】【ble 介绍 1】【什么是RPA】
  • DDS信号发生器设计
  • 自编码网络深度解析:原理、数学推导与实现细节
  • 标易行项目redis内存中放哪些数据
  • linux多线(进)程编程——(7)消息队列
  • 熟悉Linux下的编程
  • MySQL分组查询和子查询
  • secsgem v0.3.0版本使用说明文档
  • 探索 C 与 Java/Kotlin 的语言差异:从指针到高阶函数
  • 深入定制 QSlider——实现精准点击跳转与拖拽区分
  • 用Python手搓一个简单的饭店管理系统(上篇)
  • 依赖注入(DI)与自动装配的深度分析:优势、局限与实践考量
  • 智慧城市:如同为城市装上智能大脑,开启智慧生活
  • 以优良作风激发改革发展动力活力,中管企业扎实开展深入贯彻中央八项规定精神学习教育
  • 姜仁华任中国水稻研究所所长,胡培松院士卸任
  • 杭州:调整个人购买家庭住房享受契税优惠住房套数查询规则
  • 一镇一链、一园一策,上海闵行发布重点产业区镇协同产业地图
  • 涉嫌骗取贷款,洪九果品创始人夫妇及多名高管被采取刑事强制措施
  • 广东虎门大桥计划今年10月开启大修,工期27个月