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

前言

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

效果图

子组件代码

ini 复制代码
<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自带的)

父组件代码

xml 复制代码
<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组件就完成了。有需要的小伙伴可以去试试哦。

相关推荐
_codemonster37 分钟前
Vue的三种使用方式对比
前端·javascript·vue.js
wqq63108553 小时前
Python基于Vue的实验室管理系统 django flask pycharm
vue.js·python·django
Deng9452013143 小时前
Vue + Flask 前后端分离项目实战:从零搭建一个完整博客系统
前端·vue.js·flask
Hello.Reader3 小时前
Flink 文件系统通用配置默认文件系统与连接数限制实战
vue.js·flink·npm
EchoEcho5 小时前
深入理解 Vue.js 渲染机制:从声明式到虚拟 DOM 的完整实现
vue.js
C澒6 小时前
Vue 项目渐进式迁移 React:组件库接入与跨框架协同技术方案
前端·vue.js·react.js·架构·系统架构
发现一只大呆瓜7 小时前
虚拟列表:从定高到动态高度的 Vue 3 & React 满分实现
前端·vue.js·react.js
鱼毓屿御7 小时前
如何给用户添加权限
前端·javascript·vue.js
Java新手村8 小时前
基于 Vue 3 + Spring Boot 3 的 AI 面试辅助系统:实时语音识别 + 大模型智能回答
vue.js·人工智能·spring boot
雯0609~8 小时前
hiprint:实现项目部署与打印3-vue版本-独立出模板设计与模板打印页面
前端·vue.js·arcgis