index.vue 7.98 KB
<template>
  <el-select :key="forceKey"
             ref="selectRef"
             v-select-load-more="loadMore"
             :value="value"
             v-bind="selectProps"
             v-on="selectEvent"
             @change="handleSelectChange"
             @visible-change="handleVisibleChange">
    <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, uniqBy } 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,
		},
		immediate: {
			default: false,
			type: Boolean,
		},
		optionProps: {
			default: () => ({}),
			type: [Object, Function],
		},
		options: {
			default: () => ([]),
			type: Array,
		},
		value: {
			required: true,
		},
		fieldName: {
			type: Object,
			default: () => ({
				label: "label",
				value: "value",
			}),

		},
		defaultValue: {
			type: Object,
			default: () => ({
				label: "",
				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) {
			if (!isFunction(this.fetchApi)) {
				console.log("不是个函数?", this.fetchApi);
				return;
			}
			this.loading = true;
			try {
				const { fieldName: { value, label } } = this;
				const { list, query } = await this.fetchApi({
					// 组件内部的 查询
					pageQuery: this.pageQuery,
					// 组件内部维护的options列表
					localOptions: this.localOptions,
					// 是否加载更多触发的
					loadMore,
					// 是否第一次触发
					isImmediate,
				});
				const { defaultValue } = this;

				if (loadMore) {
					// 加载更多时,如果默认值已存在则移除,避免重复
					if (defaultValue.value) {
						const existIndex = list.findIndex(item => item[value] == defaultValue.value);
						if (existIndex > -1) {
							list.splice(existIndex, 1);
						}
					}
					// 将新数据追加到现有选项后面
					this.localOptions = uniqBy([...this.localOptions, ...list], value);
				} else {
					// 首次加载或搜索时,如果有默认值则添加到列表开头
					if (defaultValue.value && defaultValue.label) {
						// 检查默认值是否已在列表中,避免重复添加
						const exists = list.some(item => item[value] == defaultValue.value);
						if (!exists && list.length > 0 && !this.pageQuery.searchValue) {
							list.unshift({
								[value]: defaultValue.value,
								[label]: defaultValue.label,
							});
						}
					}
					this.localOptions = list;
				}
				this.$emit("update:options", this.localOptions);
				Object.assign(this.pageQuery, query);
			} finally {
				this.$nextTick(() => {
					this.loading = false;
				});
			}
		},
		handleSelectChange(e, d) {
			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>