最近想着使用Vue3+ElementPlus封装一个后台管理常用的Table组件,设计之初考虑到高自定义性,所以便延伸出以下的代码
使用技术栈:
- Vue3.x
- ElementPlus
- Jsx
Jsx 采用的并不是Vue提供的原生h函数,而是类似React的语法.
npm install @vue/babel-plugin-jsx -D
Link
具体代码如下:
// EasyTable.jsx
import { defineComponent } from "@vue/runtime-core";
import styles from "./EasyTable.module.css";
export default defineComponent({
props: {
table: {
type: Object,
required: true,
},
},
setup(props) {},
render() {
const { data, tr } = this.table;
return (
<div className={styles["base-layout"]}>
<Table border data={data}>
{tr.map((column) => {
return column.template ? (
<TableColumn
width={column.width}
key={column.id}
label={column.label}
>
{this.$slots[column.template]
? this.$slots[column.template](column)
: ""}
</TableColumn>
) : (
<TableColumn
prop={column.prop}
label={column.label}
width={column.width}
key={column.id}
/>
);
})}
</Table>
</div>
);
},
});
// Home.vue 使用 <template> <div class="home"> <EasyTable :table="table"> <template v-slot:gender="column"> <div>{{ column.gender ? "女" : "男" }}</div> </template> </EasyTable> </div> </template> <script> import EasyTable from "@/components/EasyTable"; export default { name: "Home", components: { EasyTable, }, data() { return { table: { data: [ { name: "纪晓岚", age: 18, job: "大学士", gender: 0, desc: "目不识丁纪学士", }, { name: "和珅", age: 18, job: "军机大臣", gender: 0, desc: "两袖清风和大人", }, ], tr: [ { label: "姓名", prop: "name", width: "180", }, { label: "年龄", prop: "age", width: "180", }, { label: "性别", width: "180", template: "gender", }, { label: "特征", prop: "desc", }, ], }, }; }, methods: { onClick() { alert("Hello World"); }, }, }; </script>
浙公网安备 33010602011771号