select选择器实现下拉加载更多
可以将此细分为,1.下拉到底部; 2.触发请求; 3.加载,难点便只是在下拉到底部。
我们要想知道是否已经触底,首先找到拥有滚动条的元素
在select 添加 ref
<template>
<el-select v-model="value" ref="select" placeholder="请选择" :loading="loading">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
name: "selectPage",
data(){
return{}
},
mounted(){
console.log(this.$refs.select)
},
}
</script>
我们可以找到滚动条在此元素,接下来便好办了,监听滚动条滑动并添加事件
mounted(){
console.log(this.$refs.select)
this.$refs.select.$refs.scrollbar.$refs.wrap.addEventListener('scroll',this.scolling)
},
methods:{
scolling(){
let e = this.$refs.select.$refs.scrollbar.$refs.wrap
if(this.noMore) return
// 到底时触发 loadMore
let loadMore = e.scrollHeight - e.scrollTop <= e.clientHeight
if(loadMore){
this.loadMore()
}
}
}
以下贴出完整代码
<template>
<el-select v-model="value" ref="select" placeholder="请选择" :loading="loading">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
name: "selectPiping",
props:{
api: String,
pageSize: {type: Number , default : 10},
method: {type: String , default: 'post'},
params: {type: Object , default: {} }
},
data(){
return{
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}, {
value: '选项3',
label: '蚵仔煎'
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}],
loading: false,
pageNo: 1,
noMore: false
}
},
mounted(){
this.$refs.select.$refs.scrollbar.$refs.wrap.addEventListener('scroll',this.scolling)
},
methods:{
scolling(){
let e = this.$refs.select.$refs.scrollbar.$refs.wrap
if(this.noMore) return
let loadMore = e.scrollHeight - e.scrollTop <= e.clientHeight
if(loadMore){
this.loadMore()
}
},
loadMore(){
if(this.loading) return
this.loading = true
let {api,method,params,pageNo,pageSize} = this
Object.assign(params,{pageNo,pageSize})
this.http({url:api, config: {method:method , params:params }}).then((res)=>{
if(pageNo === res.totalPage){
// 获取到最后的值时,不再监听滚动条的动作,移除滚动事件
this.$refs.select.$refs.scrollbar.$refs.wrap.removeEventListener('scroll',this.scolling())
this.noMore = true
}
this.pageNo++
this.options.push(res)
}).finally(()=> this.loading = false)
}
}
}
</script>
<style scoped>
</style>