封装后调用组件效果:
<Table :tableData="tableData" :tableColumn="tableColumn">
<template #status="scope: any">
<el-switch v-model="scope.data.status" :active-value="0" :inactive-value="1" />
</template>
<template #operation="scope: any">
<el-button type="primary" plain @click="edit(scope.data)">编辑</el-button>
<el-button type="danger" plain @click="del(scope.data)">分配角色</el-button>
</template>
</Table>
组件中接收变量含义:
tableData:表数据;(默认数组)
tableColumn: 表头项;(默认数组)
tableColumn-prop:列的英文名;(默认字符串)
tableColumn-label:列的中名;(默认字符串)
tableColumn-width:列的宽度;(默认字符串)
tableColumn-expand:是否扩展列;(默认布尔值)
<template>
<div class="">
<el-table :data="tableData" style="width: 100%">
<el-table-column
v-for="item in tableColumn"
:key="item.prop"
:prop="item.prop"
:label="item.label"
:width="item.width"
>
<template #default="scope">
<slot
v-if="item.expand"
:name="item.prop"
:data="scope.row"
:index="scope.$index"
></slot>
<div v-else>{{ scope.row[item.prop] }}</div>
</template>
</el-table-column>
</el-table>
</div>
</template>
- 利用vue3的作用域插槽,使得在列表项有需要增加按钮文本的时候,插入代码,动态生成结构,有利于多次复用组件,减少代码冗余。
如何调用?
- 先引入并写上双标签;
- 定义tableData以及tableColumn的值;
- 使用template搭配作用域插槽,#
列名
=“scope”;
PS:tableColumn示例:
const tableColumn: any = reactive([
{
prop: 'id',
label: '编号',
width: '',
expand: false
},
{
prop: 'nickName',
label: '账号',
width: '',
expand: false
},
{
prop: 'username',
label: '姓名',
width: '',
expand: false
},
{
prop: 'email',
label: '邮箱',
width: '',
expand: false
},
{
prop: 'createTime',
label: '创建时间',
width: '',
expand: false
},
{
prop: 'loginTime',
label: '登录时间',
width: '',
expand: false
},
{
prop: 'status',
label: '状态',
width: '',
expand: true
},
{
prop: 'operation',
label: '操作',
width: '180',
expand: true,
}
])
完~~