Vue+TypeScript 封装ElementUI的Descriptions组件
1.在components下新建组件文件夹
2.写入vue文件
<template> <el-descriptions :title="title" :column="column" :border="border" :direction="direction" :labelStyle="{ width: '15rem' }" > <el-descriptions-item v-for="(item, index) in columns" :key="index" :label="item.label" > <slot v-if="item.slot" :scope="comData[item.prop]" :name="item.slot" /> <template v-else>{{ comData[item.prop] }}</template> </el-descriptions-item> </el-descriptions> </template> <script lang="ts"> import viewTS from "./index"; export default viewTS; </script>
3.写入ts文件
import "./index.less"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Prop, Watch } from 'vue-property-decorator'; @Component export default class DescriptionsTS extends Vue { //标题 @Prop({ type: String, required: false, default: "" }) private title!: string; // 数据列表 @Prop({ type: Object, required: true, default: {} }) private data!: any; // 需要展示的列 === prop:列数据对应的属性,label:列名// 描述列表 item的控制参数 @Prop({ type: Array, required: true, default: [] }) private columns!: Array<any>; //一行 Descriptions Item 的数量 @Prop({ type: Number, required: false }) private column?: number; //是否带边框 @Prop({ type: Boolean, required: false }) private border?: boolean; //排列的方向 @Prop({ type: String, required: false }) private direction?: string; comData = this.data; @Watch('data') public watchData(newVal: boolean) { this.comData = newVal; } }
3.写入less文件(这里我就不写了,自己根据需求写就好)
4.在components的index.ts文件下导出此组件
import Descriptions from "./descriptions/index.vue"; export { Descriptions }
然后就可以在需要的页面中使用啦
下面我们来实际使用一下
vue:
<div class="table-title">幼儿基础信息</div>
<Descriptions :data="formModel" :columns="childBaseColumns" :border="true">
<template slot="enterGardenType" slot-scope="scope">
{{ getEnterGardenTypeText(scope.scope) }}
</template>
</Descriptions>
ts:
1.注入此组件:
import { Descriptions, Upload } from "@/app/components"; @Component({ components: { Descriptions, Upload } })
2.给所需属性赋值
formModel = new SaveChildBaseInfo(); //幼儿基础信息 childBaseColumns = [ { prop: "gradeCode", label: "幼儿报名年级" }, { prop: "regNumber", label: "幼儿市登记编号" }, { prop: "childName", label: "幼儿姓名" }, { prop: "sex", label: "幼儿性别" }, { prop: "birthday", label: "幼儿出生日期" }, { prop: "householdImmigrationDate", label: "幼儿户籍迁入本市/招生范围日期" }, { prop: "isHQ", label: "是否华侨" }, { prop: "gB_MZ_Code", label: "幼儿民族" }, { prop: "transferReason", label: "插班原因" }, { prop: "enterGardenType", label: "入园方式", slot: "enterGardenType" }, ]; getEnterGardenTypeText(scope: any) { return scope == 0 ? "户籍入园" : "房产入园"; }
展示效果: