Sometimes there will be a lot of data in the select, and pagination is needed at this time, so how do we monitor the bottom of the select?
At this time we have to write a custom instruction and register it in main.js
v-load-more=‘loadMore’
1. Create a directives.js file in the same directory as main.js
import Vue from 'vue'
let MyPlugin = {}
// 定义全局指令
export default MyPlugin.install = function(vue, options) {
// loadmore 是定义的指令 名称 , 使用时 用 v-loadmore = "dosomethingFun or data"
Vue.directive('loadmore', {
// bind只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
bind (el, binding) {
// 获取element-ui定义好的scroll盒子 Select 选择器的下拉盒子
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 是指令的绑定值,该值可能是字符串,数字、函数
// binding.value() 表示执行 v-loadmore 绑定的函数
binding.value()
}
})
}
})
}
2. Apply global directives in main.js
// Vue.use 需要在 new Vue() 之前使用
// 引用创建好的指令
import directives from './directives'
// 全局注册指令
Vue.use(directives)
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
3. Use the Select selector in the project file demo.vue to call the command to monitor the scrolling loading data
<template>
// v-loadmore 是前文注册过的指令, loadMore 是指令绑定的值 相当于前文的 binding.value,由于指令值是函数,前文使用了 binding.value()执行调用
<el-select v-model="id" v-loadmore="loadMore">
<el-option v-for="item in bmList" :key="item.id" :label="item.name" :value="item.id">
</el-option>
</el-select>
</template>
<script>
import {
getBMList,
} from '@/api/store'
export default {
data(){
return {
bmList: [],
id:''
}
},
methods: {
loadMore(){
getBMList().then(res => {
const newList = res.data.data
if (newList.length > 0) {
this.bmList.push(...newList)
}
})
}
}
}
</script>