vue Element下拉框滚动加载选项数据
vue Element下拉框滚动加载选项数据(防止下拉框数据过多一次性请求过慢)
1,新建一个directives.js 文件
import Vue from 'vue'
// v-loadmore: 用于在element-ui的select下拉框加上滚动到底事件监听
Vue.directive('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();
}
});
}
})
//input输入框远程搜索时添加滚动分页加载后台数据
Vue.directive('inputloadmore', {
bind(el, binding) {
// 获取element-ui定义好的scroll盒子
const SELECTWRAP_DOM = el.querySelector('.el-autocomplete-suggestion .el-autocomplete-suggestion__wrap');
SELECTWRAP_DOM.addEventListener('scroll', function () {
const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
if (CONDITION) {
binding.value();
}
});
}
})
2.在main.js全局引用
import './utils/directives' //注意文件路径,我的放在utils文件夹下
3.select选择下拉框的完整的例子代码
<template>
<div class="tac">
<span>滚动加载下拉框选项</span>
<el-select
v-model="kolId"
placeholder="请选择"
@change="searchByKol"
filterable
v-loadmore="loadMore"
@visible-change="hideloadMore"
remote
:remote-method="remoteMethod"
@focus="getSelectValue()"
clearable
>
<el-opti