likes
comments
collection
share

Vue3.2 + Element-Plus + Ts二次封装el-table

作者站长头像
站长
· 阅读数 7

前言

最近在使用Vue3.2开发一个后台管理系统,重复写表单实在是太烦了,过于浪费时间了。所以就自己二次封装了el-table,满足现在的业务需求。使用js的话,把ts代码剔除即可(也没有两行)。

效果图

Vue3.2 + Element-Plus + Ts二次封装el-table

子组件代码

<template>
  <el-table 
  :data="tableData" 
  style="width: 100%"
  >
    <slot name="index"></slot>
    <el-table-column 
    v-for="(item) in headers" 
    :key = "item.prop"
    v-bind="item"
    show-overflow-tooltip
    />
    <slot name="operate"></slot>
  </el-table>
</template>
<script setup lang="ts">
import { defineProps, PropType } from 'vue';
type Link = {
  label: string;
  prop: string;
};
defineProps({
  headers: {
    type: Array as PropType<Array<Link>>,
    default: () => [],
  },
  tableData:{
    type: Array,
    default: () => [],
  }
})
</script>
<style scoped></style>
  • 2个插槽 一个前置位的index放多选或者index 看需求自改 ,后置位的operate放固定于表单右侧的操作按钮
  • v-bind="item" 实现动态绑定一些值,代替:width='item.width',:label="item.label"等
  • show-overflow-tooltip 字段过长一行内显示(el自带的)

父组件代码

<template>
  <HelloWorld :headers="headers" :tableData="tableData">
    <template #index>
      <el-table-column label="序號" width="100" type="index" align="center" />
    </template>
    <template #operate>
      <el-table-column fixed="right" label="Operations" width="60">
        <template #default>
          <el-button  type="primary" size="small" @click="handleClick">Detail</el-button>
        </template>
      </el-table-column>
    </template>
  </HelloWorld>
</template>
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
const handleClick =()=>{
  console.log('111222333444')
}
const headers = [
  {
    label: '机构名称',
    prop: 'date',
    width: '120',//沒有定義可以不用
    formatter:(row:any)=>{
      return row.date + 'A'
    }
  },
  {
    label: '业务字段01',
    prop: 'name',
  },
  {
    label: '业务字段02',
    prop: 'number',
    width: '160',
    sortable:true,
  }
]
const tableData = []
</script>
<style scoped></style>
  • label -- 表头名字(必传)
  • prop -- 表单值字段(必传)
  • width -- 宽度
  • formatter -- 对值进行处理显示
  • sortable --el自带的简单排序

总结

整体思路:重复性的操作都放进headers中减少重复操作(麻木工作),可能有独立操作的地方使用slot插槽提到父组件进行处理,这样一个受控的table组件就完成了。有需要的小伙伴可以去试试哦。