vue element el-select组件封装 支持懒加载 多选 回显
el-select数据过多处理方式
一种优化思路:
element-ui的select有一个remote-method,支持远程搜索,我们让服务端支持一下不就可以了,当然这是一种解决的方案。但是有时候这种方法对我并能够不适用,因为这样会出现回显问题,回显的时候是还需拿到所需option;
另一种优化思路:
下拉懒加载, 当select滚动到底部时, 你再去请求一部分数据, 加入到当前数据中.
假设我们有个下拉框是用来选择课程的:
<template>
<el-select
v-model="newValue"
:laceholder="placeholderText"
filterable
remote
clearable
:disabled="disabled"
:multiple="isMultiple"
@change="handleChange"
reserve-keyword
:remote-method="remoteMethod"
:style="styles"
:loading="loading"
v-el-select-loadmore="loadmore"
>
<el-option
v-for="item in list"
:key="item.index"
:label="item.title"
:value="item.id"
>
</el-option>
</el-select>
</template>
javascript
var timer;
export default {
props: {
value: {},
styles: {},
condition: {},
isMultiple: { default: false },
placeholderText: { default: "请选择" },
size: { default: "mini" },
disabled: { default: false },
autoLoad: { default: true },
table: {
type: String,
required: true,
},
},
// 自定义指令
directives: {
"el-select-loadmore": {
bind(el, binding) {
// 获取element-ui定义好的scroll盒子
const SELECTWRAP_DOM = el.querySelector(
".el-select-dropdown .el-select-dropdown__wrap"
);
SELECTWRAP_DOM.addEventListener("scroll", function() {
/**
* scrollHeight 获取元素内容高度(只读)
* scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
* clientHeight 读取元素的可见高度(只读)
* 如果元素滚动到底, 下面等式返回true, 没有则返回false:
* ele.scrollHeight - ele.scrollTop === ele.clientHeight;
*/
const condition =
this.scrollHeight - this.scrollTop <= this.clientHeight;
if (condition) {
binding.value();
}
});
},
},
},
data() {
return {
newValue: this.isMultiple ? [] : "",
list: [],
loading: false,
formData: {
pageNum: 1,
pageSize: 20,
},
};
},
watch: {
value: function(val) {
if (
((this.isMultiple && val.length != 0) ||
(typeof this.isMultiple == "undefined" && val != "")) &&
this.list.length == 0
) {
this.getList();
} else {
this.newVal = val;
}
},
},
mounted() {
this.getList();
},
methods: {
loadmore() {
this.formData.pageNum++;
this.getList();
},
loadData() {
if (this.autoLoad == false) return;
this.getList();
},
getList() {
this.loading = true;
var path;
switch (this.table) {
case "course":
path = "course/list";
this.pk = "id";
this.label = "title";
break; // 内部 库内课程
default:
alert("缺少组件参数");
}
this.$http.fetch(path, this.formData, this.condition).then((res) => {
console.log(res);
// this.list = res.data;
this.loading = false;
this.list = [...this.list, ...res.data];
});
},
handleChange() {
this.$emit("input", this.newValue);
},
remoteMethod(query) {
console.log(query);
// 远程搜索 逻辑
var url = "";
if (this.table == "course") {
url = "course/list";
} else {
return;
}
if (query !== "") {
this.loading = true;
clearTimeout(timer);
timer = setTimeout(() => {
this.$http.fetch(url, { search_title: query }).then((res) => {
this.loading = false;
this.list = res.data;
});
}, 500);
} else {
this.list = [];
}
},
},
};
到这里组件就已经编写完成了,现在只要在使用页面调取组件就可以使用了
现在来看一下调用组件之后的页面
选择之后的页面
支持多选 单个删除 一键删除 回显
这样就做到了滚动懒加载, 具体细节在使用时修改.