組件主要代碼:
// directives.js
import Vue from 'vue'
export default{
install() {
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.offsetHeight
if (CONDITION) {
binding.value()
}
// console.error('當(dāng)前監(jiān)聽到的滾動值', CONDITION, '當(dāng)前DOM', SELECTWRAP_DOM)
// console.error('獲取的計(jì)算值', this.scrollHeight, this.scrollTop, this.offsetHeight)
})
}
})
}
}
全局聲明:
// 注冊滾動條加載觸發(fā)事件v-loadmore綁定
import loadmore from './directive/loadmore'
Vue.use(loadmore)
VUE頁面引用組件使用:
<el-select
@change="getCourseInfo($event)"
filterable
remote
v-model="postForm.offlineProdInfo.prodId"
placeholder="請搜索線下課程"
v-loadmore="loadMore"
clearable
:remote-method="remoteMethod"
:loading="listLoading"
>
<el-option
v-for="item in courseList"
:key="item.id"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
loadMore() {
// 這里寫入要觸發(fā)的方法
console.log('我到底滾動了')
if (this.loadFlag) {
this.courseQuery.pageNo++
this.getofflineCourseList()
}
},
async getofflineCourseList() {
this.listLoading = true
const res = await offlineCourseList(this.courseQuery).catch(() => false)
this.listLoading = false
if (!res) return
const { records, total, size, current } = res.data.data
// this.courseList = records || []
this.courseList = this.courseList.concat(records)
this.courseQuery.total = total || 0
if (size * current >= total) {
// 最后一頁了
this.loadFlag = false
}
},
async remoteMethod(query) {
console.log('觸發(fā)檢索方法')
if (query !== '') {
this.courseQuery.name = query
} else {
this.courseQuery.name = ''
this.courseList = []
}
this.listLoading = true
const res = await offlineCourseList(this.courseQuery).catch(() => false)
this.listLoading = false
if (!res) return
const { records, total } = res.data.data
this.courseList = records || []
this.courseQuery.total = total || 0
},