ElementUi 表格组件二次封装

引言

后台管理系统中,大量用到了el-table,而且显示的内容不同,基本是从接口获取,如果每个界面都写el-table,容易造成难以维护的局面,因此二次封装了el-table组件

el-table二次封装的组件代码

<template>
  <div>
    <el-table :data="tableData" stripe border style="width: 100%">
      <template v-for="(item, index) in tableOptions">
        <el-table-column
          v-if="item.prop"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :min-width="item.minWidth"
        ></el-table-column>
        <el-table-column
          v-else
          :key="index"
          :label="item.label"
          :width="item.width"
          :min-width="item.minWidth"
        >
          <template slot-scope="scope">
            <slot :name="item.slotName" :row="scope.row"></slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
export default {
  props: {
    // 表格数据
    tableData: {
      type: Array
    },
    // 表格配置
    tableOptions: {
      type: Array
    }
  }
};
</script>

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

属性详情

在这里插入图片描述在这里插入图片描述

父组件使用

//引入组件
import MyTable from '@/components/MyTable';

//注册
components: {
  MyTable
}

//表格数据
departmentData: [
  {
    company: {
      content: '公司介绍11',
      id: 1,
      nickname: 'dddd',
      phoneNumber: '11111111111'
    },
    companyId: 1,
    id: 1,
    index: 1,
    nickname: '全公司'
  },
  {
    company: {
      content: '公司介绍11',
      id: 2,
      nickname: 'dddd',
      phoneNumber: '11111111111'
    },
    companyId: 2,
    id: 2,
    index: 2,
    nickname: '全公司'
  }
],
      
// 表格配置
tableOptions: [
  // prop 字段名称根据接口返回处理的数据的列字段名称一致
  {
    prop: 'index',
    label: '序号',
    width: '80'
  },
  // 需要对列数据进行处理,不写prop字段,使用slotName字段
  {
    label: '公司名称',
    slotName: 'companyName'
  },
  {
     prop: 'nickname',
     label: '部门名称'
  },
  {
     label: '操作',
     slotName: 'operate',
     width: '150'
  }
]
//在需要的位置使用
    <my-table :tableData="departmentData" :tableOptions="tableOptions">
      <!-- 公司名称 -->
      <template slot="companyName" slot-scope="scope">
        <span v-if="scope.row.company">
          {{ scope.row.company.nickname }}
        </span>
        <span v-else>{{ companyName }}</span>
      </template>
      <!-- 操作 -->
      <template slot="operate" slot-scope="scope">
        <el-button
          type="primary"
          size="small"
          @click="editDepartment(scope.row)"
          >修改</el-button
        >
        <el-button
          type="info"
          size="small"
          @click="delDepartment(scope.row)"
          >删除</el-button
        >
      </template>
    </my-table>   

结尾

通过二次封装,便可以减少每个界面直接使用el-table,便于维护,需要其余字段也方便直接在封装的组件中加入,而且二次封装的组件也方便在其余项目中使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值