el-select 结合 自定义指令 实现分页加载

一. 自定义指令 注册

// 注册滚动条加载触发事件v-loadmore绑定
import { debounce } from '@/utils'; // 防抖
export default {
  inserted(el, binding) {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    SELECTWRAP_DOM.addEventListener('scroll', debounce(function () {
      const CONDITION = parseInt(this.scrollHeight - this.scrollTop) <= this.clientHeight
      if (CONDITION) {
        binding.value()
      }
    },100))
  }
}

使用

  <template>
  <div id="SelectDown">
    <el-select
      v-model="query.projectId"
      filterable
      :clearable="clearable"
      size="small"
      style="width: 240px"
      placeholder="请选择在建工程"
      :filter-method="selectFilter"
      v-loadmore="loadMore"
      @change="SelectChange"
    >
      <el-option
        v-for="(item, index) in projectList"
        :key="index"
        :label="item.projectName"
        :value="item.projectId"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
// v-loadmore 为自定义指令 监听滚动条
import { getSelectPageList } from "../../api/project/project";
export default {
  name: "SlectDown",
  props: ["flagDefault"], // flagDefault 是否默认显示第一个
  data: () => ({
    query: {
      total: 0,
      pageSize: 10,
      pageNum: 1,
      projectId: "",
    },
    clearable: true,
    projectList: [],
    count: 0
  }),
  async created() {
    await this.getSelectPageList();
    this.$nextTick(() => {
      // this.query.projectId = this.flagDefault? this.projectList[0].projectId: "";
      if (this.flagDefault) {
        this.query.projectId = this.projectList[0].projectId
        this.clearable = false // 默认显示 则不能删除
      }
    });
  },
  mounted() {},
  watch: {
    query: {
      handler(newQuery) {
        this.count++
        if (newQuery.projectId && this.count === 3) {
          this.$emit("projectSelect", this.query.projectId);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    async getSelectPageList() {
      const { rows, total } = await getSelectPageList(this.query);
      this.projectList = this.projectList.concat(rows);
      this.query.total = total;
    },
    // 搜索
    selectFilter(value) {
      this.query.pageNum = 1;
      setTimeout(() => {
        this.query.projectName = value;
        this.projectList = [];
        this.getSelectPageList();
      }, 100);
    },
    // 加载更多
    loadMore() {
      this.query.pageNum++;
      this.getSelectPageList();
    },
    // 工程选中
    SelectChange (value) {
      // 发送事件 父组件接收值即可
      this.$emit('projectSelect', value)
    }
  },
};
</script>

<style scoped lang="scss">
</style>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容