vue3+el-select实现触底加载更多功能(ts版)

来自:网络
时间:2023-07-25
阅读:
目录

思路

使用全局指令来实现触底加载功能

通过el-select中的popper-class给下拉框加入一个类名

在src下的utils文件夹中创建selectLoadMoreDirective.ts文件

import { Directive, DirectiveBinding } from 'vue'
const loadMore: Directive = {
  beforeMount(el: any, binding: DirectiveBinding) {
    console.log(el)
    const selectDom = (document.querySelector(".more_select_dropdown") as any).querySelector(".el-select-dropdown .el-select-dropdown__wrap");
    console.log(selectDom, 'selectDom++++++++++++++');
    function loadMores(this: any) {
      const isBase = this.scrollHeight - this.scrollTop <= this.clientHeight
      if (isBase) {
        binding.value && binding.value()
      }
    }
    el.selectDomInfo = selectDom
    el.userLoadMore = loadMores
    nextTick(() => {
      selectDom?.addEventListener('scroll', loadMores)
    })
  },
  beforeUnmount(el: any) {
    if (el.userLoadMore) {
      el.selectDomInfo.removeEventListener('scroll', el.userLoadMore)
      delete el.selectDomInfo
      delete el.userLoadMore
    }
  }
}
export default loadMore

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from '/@/router'
import loadMore from '@/utils/selectLoadMoreDirective'
const app = createApp(App)
app.use(router)
app.directive('loadMore', loadMore)

home.vue

<template>
  <div class="p-2">
    <el-select v-model="selectedValue" v-loadMore="loadMore" class="more-select" popper-class="more_select_dropdown"
      @change="selectChange">
      <el-option v-for="(item, index) in list" :key="`${item.value}${index}`" :label="item.label" :value="item.value" />
    </el-select>
  </div>
</template>
<script setup name="Home" lang="ts">
import { ComponentInternalInstance, computed, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs } from 'vue';
const selectedValue = ref([])
const selectData = reactive({
  pageIndex: 1,
  pageSize: 5,
  finished: false
})
const list = ref([
  {
    value: 1,
    label: '测试1'
  },
  {
    value: 2,
    label: '测试2'
  },
  {
    value: 3,
    label: '测试3'
  },
  {
    value: 4,
    label: '测试4'
  },
  {
    value: 5,
    label: '测试5'
  },
  {
    value: 6,
    label: '测试6'
  },
  {
    value: 7,
    label: '测试7'
  },
  {
    value: 8,
    label: '测试8'
  },
])
//触底函数
const loadMore = () => {
  console.log(' 触底了');
  // 防抖处理
  setTimeout(() => {
    if (selectData.finished) return //值为true,则代表没有数据了
    selectData.pageIndex += 1
    // list.value = list.value.concat(list2.value)
    for (let i = 1; i <= 8; i++) {
      list.value.push({
        value: i,
        label: `测试${i}`
      })
    }
  }, 500)
}
//选中值发生变化时触发
const selectChange = () => {
  console.log('选中的xxxx')
}
</script>
返回顶部
顶部