vue3+el-select实现触底加载更多功能(ts版)
作者:我总是词不达意
这篇文章主要给大家介绍了基于vue3和el-select实现触底加载更多功能,文中有详细的代码示例,感兴趣的同学可以借鉴参考下
思路
使用全局指令来实现触底加载功能
通过
el-select
中的popper-class
给下拉框加入一个类名
在src下的utils文件夹中创建selectLoadMoreDirective.ts文件
import { Directive, DirectiveBinding } from 'vue' const loadMore: Directive = { beforeMount(el: any, binding: DirectiveBinding) { console.log(el) const selectDom = (document.querySelector(".more_select_dropdown") as any).querySelector(".el-select-dropdown .el-select-dropdown__wrap"); console.log(selectDom, 'selectDom++++++++++++++'); function loadMores(this: any) { const isBase = this.scrollHeight - this.scrollTop <= this.clientHeight if (isBase) { binding.value && binding.value() } } el.selectDomInfo = selectDom el.userLoadMore = loadMores nextTick(() => { selectDom?.addEventListener('scroll', loadMores) }) }, beforeUnmount(el: any) { if (el.userLoadMore) { el.selectDomInfo.removeEventListener('scroll', el.userLoadMore) delete el.selectDomInfo delete el.userLoadMore } } } export default loadMore
main.ts
import { createApp } from 'vue' import App from './App.vue' import router from '/@/router' import loadMore from '@/utils/selectLoadMoreDirective' const app = createApp(App) app.use(router) app.directive('loadMore', loadMore)
home.vue
<template> <div class="p-2"> <el-select v-model="selectedValue" v-loadMore="loadMore" class="more-select" popper-class="more_select_dropdown" @change="selectChange"> <el-option v-for="(item, index) in list" :key="`${item.value}${index}`" :label="item.label" :value="item.value" /> </el-select> </div> </template> <script setup name="Home" lang="ts"> import { ComponentInternalInstance, computed, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs } from 'vue'; const selectedValue = ref([]) const selectData = reactive({ pageIndex: 1, pageSize: 5, finished: false }) const list = ref([ { value: 1, label: '测试1' }, { value: 2, label: '测试2' }, { value: 3, label: '测试3' }, { value: 4, label: '测试4' }, { value: 5, label: '测试5' }, { value: 6, label: '测试6' }, { value: 7, label: '测试7' }, { value: 8, label: '测试8' }, ]) //触底函数 const loadMore = () => { console.log(' 触底了'); // 防抖处理 setTimeout(() => { if (selectData.finished) return //值为true,则代表没有数据了 selectData.pageIndex += 1 // list.value = list.value.concat(list2.value) for (let i = 1; i <= 8; i++) { list.value.push({ value: i, label: `测试${i}` }) } }, 500) } //选中值发生变化时触发 const selectChange = () => { console.log('选中的xxxx') } </script>
到此这篇关于vue3+el-select实现触底加载更多功能的文章就介绍到这了,更多相关vue3+el-select 加载更多功能内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!