提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
vue3 + ts + vite+ element Plus table 表格组件简单的封装
第一步 子组件
在components文件夹下新建table.vue文件(也就是子组件)
代码如下(示例):
<!-- table组件 -->
<template>
<el-table :data="tableDataList" border style="width: 100%" height="250" @selection-change="handleSelectionChange">
<el-table-column type="selection" align="center" width="55" v-if="prop.tableData.selection?prop.tableData.selection:false"/>
<el-table-column type="index" align="center" v-if="prop.tableData.index?prop.tableData.index:false" width="55" label="序号" />
<el-table-column v-for="(item,index) in prop.tableData.list" :key="index" align="center" :prop="item.prop" :label="item.label" :width="item.width"/>
<el-table-column v-if="prop.tableData.btn" label="操作">
<template #default="scope">
<el-button
v-for="ope in prop.tableData.btn"
:key="ope.id"
:type="ope.type"
@click="btn(scope.row,ope.id)"
>{{ope.name}}</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script setup lang="ts">
import { defineProps, defineEmits, } from 'vue'
const prop = defineProps(['tableData','tableDataList'])
const emits = defineEmits(['rowClick','btnClick'])
const handleSelectionChange = (row:any) => {
emits('rowClick', row)
}
const btn = (row:object,id:number) =>{
emits('btnClick', row,id)
}
</script>
<style scoped></style>
第二步 父组件
在需要使用的页面(父组件)中引入被封装的子组件(table组件)
代码如下(示例):
<template>
<Table @rowClick="rowClick" @btnClick="btnClick" :tableData="tableData" :tableDataList="tableDataList" />
</template>
<script setup lang="ts">
import Table from './components/table.vue'
import { ref } from 'vue';
type tableList = {
date: string;
name: string;
address: string;
}
interface List {
selection: boolean;
index: boolean;
list: object[];
btn: object[];
}
//表格显然的数据
const tableDataList = ref<tableList[]>([
{
date: '2023-10-01',
name: '张三',
address: '北京市昌平区',
},
{
date: '2023-10-02',
name: '李四',
address: '北京市朝阳区',
},
{
date: '2023-10-03',
name: '王五',
address: '北京市海淀区',
}
],
)
//表头数据等
const tableData = ref<List>(
{
selection: true,
index: true,
list: [
{
label: "日期",
prop: "date",
width: "200",
},
{
label: "姓名",
prop: "name",
width: "200",
},
{
label: "地址",
prop: "address",
width: "200",
},
],
btn: [
{
id: 1,
name: '编辑',
type: 'success'
},
{
id: 2,
name: '删除',
type: 'success'
},
]
}
)
const rowClick = (row: object) => {
console.log( row)
}
const btnClick = (row:object,id:number) =>{
console.log( id)
console.log( row)
}
总结
提示:表格中封装多选框,序号,和按钮的功能: