element-ui select 下拉框做成下拉加载更多

发布于:2024-05-10 ⋅ 阅读:(33) ⋅ 点赞:(0)

注意: vue 版本需要 ≥ 3.3

1、html

<el-select
	v-model="relation_type"
	placeholder="请选择合作类型"
	ref="select"
>
	<el-option
		v-for="item in cooperationTypeList"
		:key="item.value"
		:label="item.label"
		:value="item.value"
	/>
</el-select>

2、主文件

import { useElSelectionInfinityScroll } from '@/utils/combinationFunc';
setup(props, context) {
	const data = reactive({
		noMore: false,
		loading: false,
		cooperationTypeList: []
	});
	const { proxy } = getCurrentInstance();
	const loadMore = () => {
		if (data.loading) return;
		data.loading = true;
		if (proxy.cooperationTypeList.length > 40) {
			// 获取到最后的值时,不再监听滚动条的动作,移除滚动事件
			data.noMore = true;
		}
		proxy.cooperationTypeList.push(...proxy.cooperationTypeList);
		data.loading = false;
	};
	onMounted(() => {
		const elem = proxy.$refs.select.$refs.scrollbar.$refs.wrap;
		useElSelectionInfinityScroll(elem, loadMore, () => data.noMore);
	});
}

自行补充接口调用相关方法

3、 @/utils/combinationFunc.js

import { onUnmounted, toValue, watchEffect } from 'vue';
import { Throttle } from '@/utils/debunce';

export function useElSelectionInfinityScroll(target, callback, noMore) {
	onUnmounted(() => target.removeEventListener('scroll', Throttle(scolling, 300)));
	const scolling = () => {
		if (toValue(noMore)) return;
		const canLoadMore = target.scrollHeight - target.scrollTop <= target.clientHeight;
		if (canLoadMore) {
			callback();
		}
	};
	watchEffect(() => { scolling(); });
	target.addEventListener('scroll', scolling);
}

网站公告

今日签到

点亮在社区的每一天
去签到