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

相关推荐
Swift社区6 分钟前
用 RN 的渲染模型,反推 Vue 列表的正确拆分方式
前端·javascript·vue.js
Violet_YSWY10 分钟前
Vue-Pinia defineStore 语法结构
前端·javascript·vue.js
全栈陈序员10 分钟前
v-if 和 v-for 的优先级是什么?
前端·javascript·vue.js·学习·前端框架·ecmascript
全栈陈序员16 分钟前
你对 SPA 单页面应用的理解?它的优缺点分别是什么?如何实现 SPA 应用?
前端·vue.js·学习·前端框架·vue
用户8417948145629 分钟前
vue 甘特图 vxe-gantt 任务里程碑和依赖线的使用
vue.js
AAA阿giao31 分钟前
Vue3 调用 Coze 工作流:从上传宠物照到生成冰球明星的完整技术解析
前端·vue.js·coze
全栈陈序员34 分钟前
请描述下你对 Vue 生命周期的理解?在 `created` 和 `mounted` 中请求数据有什么区别?
前端·javascript·vue.js·学习·前端框架
前端无涯2 小时前
React/Vue 消息订阅发布:实现方式、开发避坑与面试核心考点
前端·javascript·vue.js
Rysxt_2 小时前
Vue 3 项目核心:main.ts 文件的作用与配置详解
前端·javascript·vue.js
Rysxt_3 小时前
Vue 3 项目核心:App.vue 文件的作用与配置详解
前端·javascript·vue.js