vue3 | el-table表格二次封装

需求

1.统一样式,通过slot插槽而非json配置项的形式,来兼容原有table的template写法,方便改造
2.列的显示隐藏控制,默认根据接口数据是否有返回绑定prop对应的字段,来实现列的权限控制显隐,也可通过外部传tableHeader来自行控制
3.合并分页器

myTable.vue

<!--
 * @Description: 公共table组件,可含分页器
 * @使用方法:将<el-table>标签名替换为<my-table>即可, v-loading 指令需改为 :loading 绑定,其他所有属性方法的绑定和使用都和element-plus的table一致
 * @个别事项: 
    1. 使用分页器需绑定 showPagination, 并传一个json配置参数 paginationConfig, 除了 @size-change 和 @current-change 两个方法直接绑定在table上外,分页器的其他原有属性统一加到 paginationConfig
    2. tableHeader:默认只会渲染显示列表接口有返回的字段对应的prop列, 传了 tableHeader 则只会渲染 tableHeader 里有定义的字段列

 * @例:
    <my-table
      :loading="loading"
      :data="tableData.data"
      @selection-change="selectTableChange"
      @cell-click="selectRowFun"
      :multipleSelection="multipleSelection"
      showPagination
      :paginationConfig="paginationConfig"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="150"></el-table-column>
      <el-table-column prop="ages" label="年龄" width="150"></el-table-column>
    <my-table/>
-->

<template>
  <el-table 
    v-bind="$attrs" 
    ref="table" 
    v-loading="loading" 
    :data="data"
    :max-height="maxHeight"
    :paginationConfig="null"
  >
    <children :key="key" />
  </el-table>
  <div class="operation-bar">
    <div class="left-operation">
      <div class="checkedCount" v-if="showCheckedCount">已选 {{ multipleSelection.length }}</div>
      <div class="operation-box">
        <slot name="operation"></slot>
      </div>
    </div>
    <div class="right-pagination">
      <pagination v-if="showPagination" :pageConfig="_paginationConfig" @size-change="pageSizeChange" @current-change="currentPageChange" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import {
    cloneVNode,
    Component,
    computed,
    reactive,
    ref,
    VNode,
    readonly,
    useSlots,
    defineExpose,
    watch,
    defineProps,
    defineEmits,
    useAttrs,
    nextTick,
    onMounted,
    onBeforeUnmount,
  } from 'vue'

  import pagination from './pagination.vue' // 分页组件
  // import useVirtualScroll from './useVirtualScroll'

  const props = defineProps({
    loading: {
      type: Boolean,
      default: false,
    },
    
    maxHeight: {
      type: [String, Number],
      default: 720,
    },

    data: {
      type: Array,
      default: () => []
    },

    // 显示已选数量
    showCheckedCount: {
      type: Boolean,
      default: false,
    },

    // 绑定的已选项数组
    multipleSelection: {
      type: Array,
      default: () => []
    },

    // 可见的字段表头 ['filed1', 'filed2', 'filed3']
    tableHeader: {
      type: Object,
      default: () => []
    },
    // 关闭自适应列宽 (用于解决列数小于3的表格在渲染时会出现数据抖动)
    closeAutoCloumnWidth: {
      type: Boolean,
      default: false
    },

    // 使用分页器
    showPagination: {
      type: Boolean,
      default: false
    },
    
    // 分页配置
    paginationConfig: {
      type: Object,
      default: () => {
        return {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes:[10, 30, 50, 100, 200, 500]
        }
      },
    },
  })

  const emit = defineEmits([
    "currentChange",
    "sizeChange",
  ]);
  

  interface IMyTableColumnProps {
    prop?: string
    label?: string
    fixed?: 'left' | 'right' | boolean
    visiable?: boolean
    index?: boolean
  }

  function isElTableColumn(vnode: VNode) {
    return (vnode.type as Component)?.name === 'ElTableColumn'
  }

  const table = ref()
  let tableHeader:any = {}
  let headerCount: number = 0
  
  const slotsOrigin = useSlots()
  const attrs:any = useAttrs()
  const slots = computed(() => {
    /* 对 slot 进行分类 */
    const main: VNode[] = [] // ElTableColumn 且存在 prop 属性
    const left: VNode[] = [] // ElTableColumn 不存在 prop 属性,但 fixed="left" 或者为 selection选框
    const other: VNode[] = [] // 其他

    // 权限控制的可见列字段
    let showKeys: string[] = [];
    
    // 方式一:只显示接口返回的字段判断 (设置了字段可见权限,接口不会返回该相关字段)
    if(props.data && props.data.length){
      let tableDataItem: any = props.data[0]
      showKeys = Object.keys(tableDataItem)
    }
    let isNullData = showKeys.length || props.tableHeader ? false : true; // 空数据时正常渲染表头

    // 方式二:用外部传来的表头字段
    console.log('外部props.tableHeader', props.tableHeader)
    if(props.tableHeader){
      tableHeader = JSON.parse(JSON.stringify(props.tableHeader));
    }

    if(JSON.stringify(tableHeader) !== '{}'){
      showKeys = Object.keys(tableHeader).map(v=>v.replace(/^./, (L) => L.toLowerCase())) // 首字母转小写
    }

    slotsOrigin.default?.()?.forEach((vnode, index) => {
      if(!vnode.props){
        vnode.props = {}
      }
      vnode.props.index = index; // 排序
      if (isElTableColumn(vnode)) {
        if(vnode.props && vnode.props.prop){
          if(!isNullData){
            vnode.props.visiable = showKeys.indexOf(vnode.props.prop) === -1 ? false : true;
          }
          
          // 构建可见列表头并缓存起来
          if(props.data && vnode.props.visiable){
            tableHeader[vnode.props.prop] = vnode.props.label
          }else{
            delete tableHeader[vnode.props.prop]
          }
        }
    
        const { prop, fixed, type } = vnode.props ?? {}
        if (prop !== undefined) return main.push(vnode)
        // if (type === 'selection' && vnode.props)  vnode.props.reserveSelection = true;
        if (fixed === 'left' || type === 'selection') return left.push(vnode)
      }
      other.push(vnode)
    })
    
    console.log('实际tableHeader',tableHeader)

    // 可见内容列少于3列则自适应宽度, 防止列数过少时撑不满table宽度出现断层
    let showMain = main.filter(v=>{return v.props && v.props.visiable !== false});
    if(!props.closeAutoCloumnWidth && showKeys.length && showMain.length < 3){
      main.forEach(vnode=>{
        if(vnode.props) vnode.props.width = ''
      })
      key.value++
    }
    if(!props.closeAutoCloumnWidth && !showMain.length && other.length && other[0].props){
      other[0].props.width = ''
      key.value++
    }

    return {
      main,
      left,
      other,
    }
  })

  /* 列的排序与部分属性 */
  const columns = reactive({

    // slot 中获取的
    slot: computed(() =>
      slots.value.main.map(({ props }) => ({
        prop: props!.prop,
        label: props!.label,
        fixed: props!.fixed,
        visiable: props!.visiable ?? true,
      }))
    ),

    // 渲染使用的
    render: computed(() => {
      const res: IMyTableColumnProps[] = []
      const slot = [...columns.slot]
      res.push(...slot)

      return res
    }),
  })

  /* 重构 slot.main */
  const refactorSlot = computed(() => {
    const { main } = slots.value

    /* 对 slot.main 进行改写 */
    const refactorySlot: VNode[] = []
    columns.render.forEach(({ prop, visiable, fixed }) => {
      if (!visiable) return

      const vnode = main.find((vnode) => prop === vnode.props?.prop)
      if (!vnode) return

      const cloned = cloneVNode(vnode, {
        fixed,
      })

      refactorySlot.push(cloned)
    })

    return refactorySlot
  })

  /* 强制更新 el-table-column */
  const key = ref(0)
  watch(refactorSlot, () => {
    if(Object.keys(tableHeader).length !== headerCount){
      // 初始表头已构建好则无需更新,否则数据刷新时会抖动闪烁
      headerCount = Object.keys(tableHeader).length;
      key.value += 1
      nextTick(()=>{
        table.value.doLayout()
      })
    }
  })

  /* 对外暴露的内容 */
  defineExpose({
    table, // el-table 实例的访问

    columns: computed(() => readonly(columns.render)),
    updateColumns(value: IMyTableColumnProps[]) {

    },
  })

  const children = () => [...slots.value.left, ...refactorSlot.value, ...slots.value.other].sort((a: any, b: any)=>a.props.index - b.props.index)
  console.log(children())

  // 合并分页配置
  const _paginationConfig = computed(() => {
    const config = {
      total: 0,
      currentPage: 1,
      pageSize: 10,
      pageSizes: [10, 30, 50, 100, 200, 500],
      layout: "total, sizes, prev, pager, next, jumper",
    };
    return Object.assign(config, props.paginationConfig);
  });

  // 切换分页
  const currentPageChange = (pageIndex: number) => {
    emit("currentChange", pageIndex);
  }
  const pageSizeChange = (pageSize: number) => {
    emit("sizeChange", pageSize);
  }


  // 虚拟滚动
  // const { visibleData, initVirtualScroll, handleSelectionAll, addListeners, removeListeners, getRowKeys} = useVirtualScroll();
  // watch(()=>props.data, ()=>{
  //   initVirtualScroll(table, JSON.parse(JSON.stringify(props.data)))
  // })

  // onMounted(()=>{
  //   addListeners()
  // })
  
  // onBeforeUnmount(()=>{
  //   removeListeners()
  // })

</script>

<style lang="less" scoped>
  .operation-bar{
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    .left-operation{
      text-align: left;
      .checkedCount{
        // padding-left: 10px;
        font-size: 14px;
        font-weight: 400;
        color: #606266;
        padding: 10px 0 10px 10px;
      }
    }
  }
</style>

pagination.vue

<template>
    <el-pagination v-bind="pageConfig"></el-pagination>
</template>
<script lang="ts" setup>
  import { defineProps } from "vue";
  defineProps({
      pageConfig: {
          type: Object,
          default: () => ({})
      }
  })
</script>

你可能感兴趣的:(vue.js,javascript,前端)