elementui 下拉框滚动加载数据-vue项目
1,新建一个js文件:directives.js,写入如下:
// directives.js
import Vue from 'vue'
//组件el-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 () {
const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight
if (CONDITION) {
binding.value()
}
})
},
})
//组件el-autocomplete
Vue.directive('loadmore2', {
bind(el, binding, vnode){
let wrapDom = el.querySelector(".el-autocomplete-suggestion__wrap")
let listDom = el.querySelector(".el-autocomplete-suggestion__wrap .el-autocomplete-suggestion__list")
wrapDom.addEventListener("scroll",(e)=>{
let condition = wrapDom.offsetHeight + wrapDom.scrollTop - 20 - listDom.offsetHeight
if(condition > 0 && !vnode.context.loading){
//滚动到底部则执行滚动方法load,binding.value就是v-scrollLoad绑定的值,加()表示执行绑定的方法
binding.value()
}
},false)
}
})
2,在vue项目目录中的main.js中使用:
/ elementui select下拉加载
import directives from './config/directives';
Vue.use(directives);
//可能会报错:Cannot read properties of undefined (reading 'install')
//解决:
export default {}.install = (Vue, options = {}) => {//防止暴力使用
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 () {
const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight
if (CONDITION) {
binding.value()
}
})
},
})
}
//注意:上面的引用可能会出错,报错:vue引用警告 "export 'default' (imported as 'url') was not found in '../config/directives'
//解决如下:
/ elementui select下拉加载
import * as directives from './config/directives';
Vue.use(directives);
3,在vue文件中使用:
HTML:
<el-form-item label="行政区:" prop="distinct">
<el-select v-model="formData.distinct" placeholder="全部" ref="selectType" clearable v-loadmore="getLoadMore">
<el-option v-for="(item,index) in administrativeList"
:key="index" :label="item.addrName" :value="item.addrName"></el-option>
<el-option v-loading="loading" value="..."></el-option>
</el-select>
</el-form-item>
JS:
data() {
return {
formData: {},
administrativeList: [
{ label: '全部', type: null },
],
loading: false,
}
},
methods() {
// 滚动加载下拉列表
getLoadMore1() {
this.loading = true;
console.log('...');
},
}