index.vue 5.94 KB
<template>
    <el-select ref="selectRef"
               :key="forceKey"
               v-select-load-more="loadMore"
               :value="value"
               v-bind="selectProps"
               v-on="selectEvent"
               @blur="handleSelectBlur"
               @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) {
				const SELECT_WRAP_DOM = el.querySelector(".el-select-dropdown .el-select-dropdown__wrap");
				SELECT_WRAP_DOM.addEventListener("scroll", function () {
					const condition
						= this.scrollHeight - this.scrollTop <= this.clientHeight;
					if (condition) {
						binding.value();
					}
				});
			},
		},
	},
	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: 15,
				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() {
		if (this.immediate) {
			await this.getApi(false, true);
		}
	},
	methods: {
		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 handleSelectBlur() {
			// 失焦时, 检查 query.searchValue的内容. 如果有值 且 options 又为空.  说明筛选到空的值
			// 需要去掉searchValue 重新获取默认的options
			if (this.pageQuery.searchValue && !this.localOptions.length) {
				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) {
				this.loading = true;
				const query = this.pageQuery;
				query.currentPage = query.currentPage + 1;
				if (query.currentPage > query.pages) {
					return;
				}
				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>