封装可以对每行进行操作的el-table

27 阅读1分钟

项目中经常会用到如下形式的table

image.png

之前每每复制一大串总觉得少了点美感,遂封装了一下,源码如下

<template>
  <el-table :data="tableData" stripe>
    <el-table-column type="index" label="序号" width="60" fixed="left" />
    <el-table-column
      v-for="item in columnList"
      :key="item.prop"
      :prop="item.prop"
      :label="item.label"
      :width="item.width"
    >
      <template v-if="item.map" #default="{ row }">
        {{ item.map[row[item.prop]] }}
      </template>
    </el-table-column>
    <!-- -------- row的操作 ------------ -->
    <el-table-column label="操作" fixed="right" width="120">
      <template #default="{ row }">
        <div class="row-operation">
          <el-icon
            :size="iconSize"
            color="#409efc"
            title="详情"
            @click="handleClick('detail', row)"
          >
            <Document />
          </el-icon>
          <el-icon
            v-if="!onlyDetail"
            :size="iconSize"
            color="#409efc"
            title="编辑"
            @click="handleClick('edit', row)"
          >
            <Edit />
          </el-icon>
          <el-icon
            v-if="!onlyDetail"
            :size="iconSize"
            color="#409efc"
            title="删除"
            @click="handleClick('delete', row)"
          >
            <Delete />
          </el-icon>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
/**
 * @description 表格组件
 * @param {Array} columnList 表格列配置
 * @param {Array} tableData 表格数据
 * @param {Number} iconSize 图标大小
 * @param {Boolean} onlyDetail 是否只显示详情操作
 * @usage <Table :columnList="columnList" :tableData="tableData" @rowReaction='handleRow' />
 */
const props = defineProps({
  columnList: {
    type: Array,
    default: () => [],
  },
  tableData: {
    type: Array,
    default: () => [],
  },
  iconSize: {
    type: Number,
    default: 22,
  },
  onlyDetail: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["rowReaction"]);
const handleClick = (type, row) => {
  emit("rowReaction", { type, row });
};
</script>

<style lang="scss" scoped>
.el-table {
  flex: 1;
  margin-bottom: 5px;
}
.row-operation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-icon {
    cursor: pointer;
  }
}
</style>


实际使用

image.png

简洁使人心情愉悦