ElementUI table表格列动态渲染
一、概述
一般写table时,列都是固定。现有业务需求,列是不固定的。根据api返回的数据,进行动态渲染。
官方table示例,链接如下:
https://element.eleme.cn/#/zh-CN/component/table
二、实现
在此基础上,增加tableHeader 变量,用来动态渲染。
test.vue
<template> <div class="root"> <el-table :data="tableData" style="width: 100%" :fit='true' :default-sort="{prop: 'date', order: 'descending'}" > <el-table-column :prop="index" :label="item" sortable show-overflow-tooltip v-for="(item, index) in tableHeader" :key="index"> </el-table-column> </el-table> </div> </template> <script> export default { name: "test", data() { return { tableHeader: { date: "日期", name: "姓名", address: "地址", }, tableData: [{ date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀区金沙江路 1517 弄', }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄', }, { date: '2016-05-03', name: '王小虎', address: '上海市普陀区金沙江路 1516 弄', }] } }, methods: { formatter(row, column) { return row.address; } } } </script> <style scoped> .root { margin: 20px 25px 0px 25px; } </style>
效果如下:
说明:
修改tableHeader 和tableData,注意对应关系即可。
:fit='true' 宽度自适应
sortable 排序
show-overflow-tooltip 当内容过长被隐藏时显示
再增加2列,修改修改tableHeader 和tableData
<template> <div class="root"> <el-table :data="tableData" style="width: 100%" :fit='true' :default-sort="{prop: 'date', order: 'descending'}" > <el-table-column :prop="index" :label="item" sortable show-overflow-tooltip v-for="(item, index) in tableHeader" :key="index"> </el-table-column> </el-table> </div> </template> <script> export default { name: "test", data() { return { tableHeader: { date: "日期", name: "姓名", address: "地址", age:"年龄", phone:"电话", }, tableData: [{ date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', age:18, phone:"12345678910", }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀区金沙江路 1517 弄', age:19, phone:"12345678911", }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄', age:20, phone:"12345678912", }, { date: '2016-05-03', name: '王小虎', address: '上海市普陀区金沙江路 1516 弄', age:21, phone:"12345678913", }] } }, methods: { formatter(row, column) { return row.address; } } } </script> <style scoped> .root { margin: 20px 25px 0px 25px; } </style>
效果如下:
本文参考链接:
https://www.jianshu.com/p/064a49f1752c