Vue element-ui 动态生成自定义table表头实现数据渲染

需求:1)表头的数据是动态的,有可能字段值很长且很多。解决方案自定义动态表头,字段长使用文字提示【el-tooltip组件】;

   2)需要对表格data中的数据值进行枚举转成中文值,且显示不同的颜色。 

效果图:

直接上代码:

1、vue代码

 1 <el-table
 2     :data="tableData"
 3     border
 4     style="width: 100%"
 5     height="100%"
 6     :header-cell-style="{
 7         'background-color': '#F0F0F0',
 8         color: '#333',
 9         'font-weight': 'normal'
10     }"
11     ref="table"
12     v-loading="tableLoading"
13 >
14     <template v-for="(item, index) in tableHeader">
15         <el-table-column
16             :prop="item.englishName"
17             :key="index"
18             show-overflow-tooltip
19             align="center"
20         >
21             <template slot-scope slot="header">
22                 <el-tooltip
23                     effect="dark"
24                     :content="item.chineseName"
25                     placement="top"
26                     class="table-header"
27                 >
28                     <span>{{ item.chineseName }}</span>
29                 </el-tooltip>
30             </template>
31             <template slot-scope="scope">
32                 <span v-if="item.englishName=='sex'" :class="{ redColor: scope.row.sex }">
33                     {{
34                         scope.row.sex ? "男" : "女"
35                     }}
36                 </span>
37                 <span v-else>{{ scope.row[item.englishName] }}</span>
38             </template>
39         </el-table-column>
40     </template>
41     <el-table-column v-if="tableHeader.length" label="操作" fixed="right">
42         <template slot-scope="scope">
43             <el-button type="text" size="mini" @click="handleDetails(scope.row)">查看</el-button>
44         </template>
45     </el-table-column>
46 </el-table>
View Code

2、tableHeader的json格式

 1 [
 2         {
 3           englishName: "date",
 4           chineseName: "日期",
 5         },
 6         {
 7           englishName: "name",
 8           chineseName: "姓名",
 9         },
10         {
11           englishName: "sex",
12           chineseName: "性别",
13         },
14         {
15           englishName: "address",
16           chineseName: "地址",
17         }
18 ]
View Code

3、表格data的json格式

 1 [
 2     {
 3         date: "2016-05-02",
 4         name: "王小虎",
 5         sex: 1,
 6         address: "上海市普陀区金沙江路 1518 弄",
 7     },
 8     {
 9         date: "2016-05-04",
10         name: "王小虎",
11         sex: 1,
12         address: "上海市普陀区金沙江路 1517 弄",
13     },
14     {
15         date: "2016-05-01",
16         name: "王小虎",
17         sex: 1,
18         address: "上海市普陀区金沙江路 1519 弄",
19     },
20     {
21         date: "2016-05-03",
22         name: "王小虎",
23         sex: 1,
24         address: "上海市普陀区金沙江路 1516 弄",
25     }
26 ]
View Code

鉴定完毕,欢迎友们一起交流学习!!

 

posted @ 2023-07-10 11:26  红石榴21  阅读(494)  评论(0编辑  收藏  举报