实现 select 滚动 options 动态加载
vue
<el-select v-model="bankName" filterable remote v-loadmore='scroll' reserve-keyword placeholder="请输入"
:remote-method="searchBank" @change="selectChange" :loading="loading">
<el-option v-for="item in bankNameOptions" :key="item.code" :label="item.value" :value="item.value"
:disabled="item.disabled"></el-option>
</el-select>
此处利用分页实现
data(){
return{
bankName:null,
loading:false,
bankNameOptions:[],
bankList:[],//暂存
query:'',
pageFlag:1,
total:null
}
},
watch:{
//监听输入值改变则重置列表
query:{
handler(val,oldVal){
if(val!==oldVal){
this.pageFlag = 1
this.bankList = []
this.bankNameOptions = []
}
console.log(val,oldVal)
},
immediate:true
}
},
//自定义指令
directives:{
loadmore:{
inserted:(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()
}
})
}
}
},
methods: {
searchBank(query) {
if (query !== '') {
this.query = query
this.loading = true;
this.initBankList()
} else {
this.bankNameOptions = [];
}
},
initBankList(){
const param = {
bankName:this.query,
pageNo:this.pageFlag,
pageSize:10
}
try {
this.bankList.length===0?this.loading = true:'';//防select闪烁
(async ()=>{
const {data} = await getBankNameList(param)//api
this.total = data.total
const datas = data.data
console.log(datas,this.total)
if(datas){
this.bankList = datas
console.log(this.bankList)
setTimeout(()=>{
this.loading = false
if(this.pageFlag>=2){
this.bankNameOptions[this.bankNameOptions.length-1].value.includes('加载中')
this.bankNameOptions.splice(this.bankNameOptions.length-1,1):''
this.bankNameOptions.push(...this.bankList)
this.bankNameOptions.push({value:'加载中...',label:'加载中...',disabled: true})
}else{
this.bankNameOptions.push(...this.bankList)
this.bankNameOptions.push({value:'加载中...',label:'加载中...',disabled: true})
}
},200)
}
})()
} catch (error) {
console.error(error)
}
},
scroll(){
if(this.pageFlag*10<this.total){
this.pageFlag = ++this.pageFlag
this.initBankList()
}else{
this.bankNameOptions[this.bankNameOptions.length-1].value.includes('加载中')?
this.bankNameOptions.splice(this.bankNameOptions.length-1,1):''
this.bankNameOptions.push({value:'没有更多数据了',label:'没有更多数据了',disabled: true})
}
},
selectChange(val){
this.bankName = val
},
}
效果