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

相关推荐
重生之后端学习1 小时前
02-前端Web开发(JS+Vue+Ajax)
java·开发语言·前端·javascript·vue.js
黄鹂绿柳4 小时前
Vue+Vite学习笔记
vue.js·笔记·学习
来自星星的坤4 小时前
【Vue 3 + Vue Router 4】如何正确重置路由实例(resetRouter)——避免“VueRouter is not defined”错误
前端·javascript·vue.js
清风细雨_林木木10 小时前
Vue 中生成源码映射文件,配置 map
前端·javascript·vue.js
繁依Fanyi12 小时前
ColorAid —— 一个面向设计师的色盲模拟工具开发记
开发语言·前端·vue.js·编辑器·codebuddy首席试玩官
codelxy12 小时前
vue引用cesium,解决“Not allowed to load local resource”报错
javascript·vue.js
Zww089114 小时前
el-dialog鼠标在遮罩层松开会意外关闭,教程图文并茂
javascript·vue.js·计算机外设
sunbyte14 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | 页面布局 与 Vue Router 路由配置
前端·javascript·vue.js·tailwindcss
苹果酱056714 小时前
React方向:react脚手架的使用
java·vue.js·spring boot·mysql·课程设计
saadiya~14 小时前
Vue 3 实现后端 Excel 文件流导出功能(Blob 下载详解)
前端·vue.js·excel