index.vue 7.13 KB
<template>
    <el-select ref="selectRef"
               :key="forceKey"
               v-select-load-more="loadMore"
               :value="value"
               v-bind="selectProps"
               v-on="selectEvent"
               @visible-change="handleVisibleChange"
               @change="handleSelectChange">
        <el-option v-for="subItem in localOptions"
                   :key="subItem[fieldName.value]"
                   v-bind="{
                       value: $attrs['value-key'] ? subItem : subItem[fieldName.value],
                       label: subItem[fieldName.label],
                       ...isFunction(optionProps) ? optionProps(subItem) : optionProps,
                   }">
            <slot name="options" :row="subItem"></slot>
        </el-option>
        <template #empty>
            <div class="temp-wrapper empty-wrapper" style="text-align: center;cursor: not-allowed;padding:4px 0;">
                <div v-if="loading">
                    <span class="el-icon-loading" />
                </div>
                <div v-else title="请键入其他关键字">
                    没有找到相关数据
                </div>
            </div>
        </template>
        <div class="temp-wrapper page-tips" title="不要点我">
            <div v-if="(pageQuery.currentPage <= pageQuery.pages) && loading">
                <span>
                    下一页加载中
                </span>
                <span class="el-icon-loading" />
            </div>
            <div v-else>
                到底没有更多了
            </div>
        </div>
    </el-select>
</template>

<script>
import { isFunction, omit } from "lodash-es";
import { nanoid } from "nanoid";

export default {
	name: "",
	directives: {
		"select-load-more": {
			bind(el, binding, vnode) {
				const getWrapDom = () => vnode.componentInstance?.$refs?.popper?.$el?.querySelector(".el-select-dropdown__wrap");
				const onScroll = function () {
					// 容差 2px,避免小数滚动高度导致触底判断抖动
					const condition = this.scrollHeight - this.scrollTop <= this.clientHeight + 2;
					if (condition) {
						binding.value();
					}
				};
				const bindScroll = () => {
					const wrapDom = getWrapDom();
					if (!wrapDom || el.__selectLoadMoreWrap === wrapDom) {
						return;
					}
					if (el.__selectLoadMoreWrap && el.__selectLoadMoreOnScroll) {
						el.__selectLoadMoreWrap.removeEventListener("scroll", el.__selectLoadMoreOnScroll);
					}
					wrapDom.addEventListener("scroll", onScroll);
					el.__selectLoadMoreWrap = wrapDom;
				};

				el.__selectLoadMoreOnScroll = onScroll;
				el.__selectLoadMoreBindScroll = bindScroll;
				setTimeout(bindScroll, 0);
				setTimeout(bindScroll, 100);
			},
			componentUpdated(el) {
				el.__selectLoadMoreBindScroll?.();
			},
			unbind(el) {
				if (el.__selectLoadMoreWrap && el.__selectLoadMoreOnScroll) {
					el.__selectLoadMoreWrap.removeEventListener("scroll", el.__selectLoadMoreOnScroll);
				}
				delete el.__selectLoadMoreWrap;
				delete el.__selectLoadMoreOnScroll;
				delete el.__selectLoadMoreBindScroll;
			},
		},
	},
	props: {
		fetchApi: {
			required: true,
			type: Function,
		},
		immediate: {
			default: false,
			type: Boolean,
		},
		optionProps: {
			default: () => ({}),
			type: [Object, Function],
		},
		options: {
			default: () => ([]),
			type: Array,
		},
		value: {
			required: true,
			type: [Array, String, Number],
		},
		fieldName: {
			type: Object,
			default: () => ({
				label: "label",
				value: "value",
			}),

		},
	},
	data() {
		return {
			localOptions: [],
			pageQuery: {
				searchValue: "",
				currentPage: 1,
				pageSize: 10,
				pages: 0,
			},
			// 初始时候为false的话. 输入文字的一瞬间会显示为空
			loading: true,
			forceKey: nanoid(),

		};
	},
	computed: {
		selectProps() {
			return {
				"collapse-tags": true,
				"filterable": true,
				"multiple": true,
				"remote": true,
				"reserve-keyword": true,
				"placeholder": "请选择",
				"remote-method": this.remoteOptions,
				...this.$attrs,
			};
		},
		selectEvent() {
			return {
				"visible-change": this.visibleChange,
				...omit(this.$listeners, ["change", "blur"]),
			};
		},

	},
	watch: {
		options: {
			handler(val) {
				this.localOptions = [...this.options];
			},
			immediate: true,
		},
	},
	async mounted() {
		console.log("初始化?");
		if (this.immediate) {
			await this.getApi(false, true);
		}
	},
	methods: {
		blur() {
			if (this.$refs.selectRef) {
				console.log("使失焦?");
				this.$refs.selectRef.blur();
			}
		},
		async getApi(loadMore = false, isImmediate = false) {
			this.loading = true;
			try {
				const { list, query } = await this.fetchApi({
					// 组件内部的 查询
					pageQuery: this.pageQuery,
					// 组件内部维护的options列表
					localOptions: this.localOptions,
					// 是否加载更多触发的
					loadMore,
					// 是否第一次触发
					isImmediate,
				});
				if (loadMore) {
					this.localOptions = this.localOptions.concat(list);
				} else {
					this.localOptions = list;
				}
				this.$emit("update:options", this.localOptions);
				Object.assign(this.pageQuery, query);
			} finally {
				this.$nextTick(() => {
					this.loading = false;
				});
			}
		},
		handleSelectChange(e) {
			this.$emit("input", e);
			if (isFunction(this.$listeners?.change)) {
				this.$listeners.change(e);
			}
		},
		async handleVisibleChange(e) {
			// 在多选的情况下  @blur响应不了  用这个替代
			if (!e) {
				// 失焦时, 检查 query.searchValue的内容. 如果有值
			// 需要去掉searchValue 重新获取默认的options
				console.log("失焦?", this.pageQuery.searchValue);
				if (this.pageQuery.searchValue) {
					console.log("重新获取默认的options");
					this.pageQuery.searchValue = "";
					// 重置页数
					this.resetPageQuery();
					await this.getApi();
				}

				if (isFunction(this.$listeners?.blur)) {
					this.$listeners.blur();
				}
			}
		},
		isFunction,
		async loadMore() {
			if (this.loading) {
				return;
			}
			const query = this.pageQuery;
			if (query.pages > 0 && query.currentPage >= query.pages) {
				return;
			}
			query.currentPage += 1;
			await this.getApi(true);
		},
		async remoteOptions(query) {
			this.loading = true;
			// 还原滚动条位置
			const wrap = this.$refs.selectRef.$refs.popper.$el.querySelector(".el-select-dropdown__wrap");
			if (wrap) {
				this.$refs.selectRef.$refs.scrollbar.moveY = 0;
				wrap.scrollTop = 0;
			}
			// this.$refs.selectRef.$refs.scrollbar.scrollTop = 0;
			// 清空选项
			this.localOptions = [];
			this.$emit("update:options", this.localOptions);

			// 重置query
			this.resetPageQuery();
			this.pageQuery.searchValue = query;
			await this.getApi();
		},
		// 重置页数.做成函数可以给父组件调用
		resetPageQuery() {
			this.pageQuery.currentPage = 1;
		},

		forceUpdate() {
			this.forceKey = nanoid();
		},
		visibleChange(show) {
			// if (!show) {
			// 	this.options = [];
			// 	this.loading = true;
			// }
		},

	},
};
</script>

<style scoped lang="scss">
.temp-wrapper {
	font-size: 14px;
	color: #606266;
	line-height: 34px;
	&.page-tips {
		cursor: not-allowed;
		padding: 0 20px;
		color: #ccc;
	}
}
</style>