在现实开发过程中经常用到el-table组件,每个表格往往重复操作。所以简单的封装下table组件,方便table,columns的设置。
export default {
methods: {
renderTable(extend = {}) {
const tableProps = {
...extend,
attrs: {
...extend.attrs,
...this.$attrs,
},
on: { ...this.$listeners, ...extend.on },
scopedSlots: { ...extend.scopedSlots },
};
return (
<el-table {...tableProps} >
{this.$scopedSlots.expand && (
<el-table-column
type="expand"
scopedSlots={{
default: scope => this.$scopedSlots.expand(scope),
}}
></el-table-column>
)}
{this.tableColumns.map(({ type, prop, renderFn, ...rest }) => {
if (type) {
return (
<el-table-column key={type} type={type} {...{ attrs: rest }}></el-table-column>
);
}
const renderer = renderFn ? renderFn : scope => <span>{scope.row[prop]}</span>;
const colScopedSlots = {
// scopedSlots需要手动绑定this(vue JSX限制)
default: (scope) => {
const { property } = scope.column;
scope.value = scope.row[property];
return renderer.call(this, scope);
},
};
return (
<el-table-column
key={prop}
scopedSlots={colScopedSlots}
{...{ attrs: rest }}
></el-table-column>
);
})}
</el-table>
);
},
},
};
创建一个表格就简单了
import columnsTable from 'xxx/table';
export default {
name: 'XXX',
mixins: [columnsTable],
computed: {
tableColumns() {
const newColumns = this.getColumns();
if (this.$scopedSlots.default) {
newColumns.push({
propsHeaderAlign: 'center',
label: '表单数据操作',
width: '180',
fixed: 'right',
renderFn: this.$scopedSlots.default,
});
}
return newColumns;
},
},
emits: [],
render() {
return this.renderTable({
attrs: {
'cell-style': { textAlign: 'center' },
'header-cell-style': { textAlign: 'center' },
},
});
},
methods: {
getColumns() {
return [
{
label: 'xxx',
prop: 'xxx',
width: '110px',
},
{
label: 'xxx',
prop: 'xxx',
},
{
label: 'xxx',
prop: 'xxx',
renderFn(scope) {
const { id_text:idText } = scope.row;
return (
<div>
<div>
<span class="test_title">{idText}</span>
</div>
</div>
);
},
},
];
},
},
};
页面中引入该表格
import Table from 'xxx/table';
<template>
<Table
border
stripe
:data="dataList"
>
<template #default="scope">
<el-link
type="danger"
>
删除
</el-link>
<el-link
type="primary"
>
修改
</el-link>
</template>
</Table>
</template>