index.vue 2.94 KB
<style>
.eagle-form-table .eagle-form-table__body td {
  padding: 5px;
}
.eagle-form-table__label {
  text-align: right !important;
  padding: 5px 15px !important;
  font-weight: bold;
  background-color: #ecf7ff;
}
.eagle-form-table__value {
  overflow: hidden;
}
</style>

<template>
  <div class="eagle-form-table el-table el-table--fit el-table--border el-table--enable-row-transition el-table--small">
    <div v-if="fullProps.title || $scopedSlots['title'] || $slots['title']" class="el-table__header-wrapper">
      <table class="el-table__header w-full" cellspacing="0" cellpadding="0">
        <thead>
          <tr class="el-table__row">
            <!-- 标题插槽 -->
            <th v-if="$scopedSlots['title'] || $slots['title']">
              <slot name="title"></slot>
            </th>
            <th v-else class="is-center">{{ fullProps.title }}</th>
          </tr>
        </thead>
      </table>
    </div>
    <div class="el-table__body-wrapper text-lg">
      <table class="el-table__body w-full" cellspacing="0" cellpadding="0">
        <tbody class="eagle-form-table__body">
          <tr v-for="(item, index) in fullProps.list" :key="index" class="el-table__row">
            <template v-if="(item instanceof Array)">
              <template v-for="(col, idx) in item">
                <td class="eagle-form-table__label" :style="labelStyle" :key="`${index}-${idx}-label`">{{ col.label }}</td>
                <td class="eagle-form-table__value" :key="`${index}-${idx}-value`" :colspan="getColspan({ item, col, idx })">
                  <component :is="col.type" v-bind="col.props" size="mini" />
                </td>
              </template>
            </template>
            <template v-else>
              <td class="eagle-form-table__label" :style="labelStyle">{{ item.label }}</td>
              <td class="eagle-form-table__value" :colspan="maxColSpan - 1">
                <component :is="item.type" v-bind="item.props" size="mini" />
              </td>
            </template>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'form-table',
  data() {
    return {
      fullProps: { ...this.$attrs, ...this.$props },
      labelStyle: { width: '80px' },
    }
  },
  computed: {
    // 配置列表中的最大列数
    maxColNum() {
      let number = 1;
      this.fullProps.list.forEach(item => {
        if (item instanceof Array) {
          if (item.length > number) {
            number = item.length;
          }
        }
      });
      return number;
    },
    // 配置列表的最大占位数
    maxColSpan() {
      return this.maxColNum * 2;
    },
  },
  methods: {
    getColspan({ item, col, idx }) {
      // 如果存在列数小于最大列数的行
      if (item.length < this.maxColNum) {
        const normalColSpan = Math.floor((this.maxColSpan - item.length) / item.length);
        return col.colspan || normalColSpan;
      }
      return 1;
    }
  }
}
</script>