Vue3+TypeScript+Element Plus 表格组件封装教程
<p>以下是一个简单的基于 Vue3、TypeScript 和 Element Plus 的表格组件封装示例:</p>
<pre><code class="language-vue"><template>
<el-table :data="tableData" :border="border" :stripe="stripe" :height="height">
<slot name="columns">
<el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label">
<template v-if="column.type && column.type === 'index'" #default="{index}">{{ index + 1 }}</template>
<template v-if="column.type && column.type === 'status'" #default="{row}">{{ getStatusText(row[column.prop]) }}</template>
<template v-if="column.type && column.type === 'action'" #default="{row}">
<el-button v-for="action in column.actions" :key="action.label" :type="action.type" @click="handleAction(action, row)">{{ action.label }}</el-button>
</template>
</el-table-column>
</slot>
</el-table>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElTable, ElTableColumn, ElButton } from 'element-plus';
export default defineComponent({
name: 'MyTable',
components: { ElTable, ElTableColumn, ElButton },
props: {
columns: { type: Array, required: true },
tableData: { type: Array, required: true },
border: { type: Boolean, default: true },
stripe: { type: Boolean, default: true },
height: { type: [String, Number] },
},
methods: {
getStatusText(status: number) {
return status === 1 ? '启用' : '禁用';
},
handleAction(action: any, row: any) {
action.handler(row);
},
},
});
</script>
</code></pre>
<p>在上述代码中,我们通过`<slot>`标签将表格列定义抽象出来,使得该组件可以适应各种不同的表格数据。同时,我们还提供了一些通用的功能,例如显示序号、显示状态文本、执行操作等。这些功能可以通过在`columns`数组中添加特定的属性来实现。例如,对于类型为`index`的列,我们可以在`columns`中这样定义:</p>
<pre><code class="language-typescript">{
label: '序号',
type: 'index',
}
</code></pre>
<p>由于`<el-table>`和`<el-table-column>`都是 Element Plus 提供的组件,因此我们需要在`<script>`中通过`import`语句将它们引入。在`<script>`中,我们还定义了组件的名字、props 和 methods。其中,`getStatusText` 和 `handleAction` 方法都是针对特定列类型的通用方法,可以通过`columns`数组中的`type`属性来调用。例如,在`columns`中这样定义一个类型为`status`的列:</p>
<pre><code class="language-typescript">{
label: '状态',
prop: 'status',
type: 'status',
}
</code></pre>
<p>在这个列中,我们需要根据`status`属性的值来显示不同的文本。因此,我们通过`getStatusText`方法来实现这个功能。另外,如果我们在`columns`中定义了一个类型为`action`的列,那么我们可以在`actions`数组中添加各种不同的操作,例如:</p>
<pre><code class="language-typescript">{
label: '操作',
type: 'action',
prop: 'id',
actions: [
{ label: '编辑', type: 'primary', handler: (row) => { /* 执行编辑操作 */ } },
{ label: '删除', type: 'danger', handler: (row) => { /* 执行删除操作 */ } },
],
}
</code></pre>
<p>通过这种方式,我们可以很方便地为表格添加各种不同的操作,而不需要每次都写一遍重复的代码。</p>
原文地址: https://www.cveoy.top/t/topic/nqij 著作权归作者所有。请勿转载和采集!