感觉手动设置 table 样式挺恶心的,而且性能也很烂,今天用 ul
+ flexbox
简单模拟一个 vue 上用的
my-table.vue
HTML
<div class="table"><ul class="tr"><li class="th" :style="styles(item)" v-for="item in columns" :key="item.key">{{item.title}}</li></ul><ul class="tr" v-for="(row, index) in data" :key="index"><liclass="td":style="styles(item)"v-for="item in columns":key="item.key"v-html="item.render?item.render(row[item.key]):row[item.key]"></li></ul></div>
JS
export default {props: {columns: {type: Array,default() {return []}},data: {type: Array,default() {return []}}},methods: {styles(item) {let { width, textAlign } = itemreturn {width: (width || 100) + 'px',textAlign: textAlign || 'left'}}}}
CSS
.table {overflow: auto;font-size: 0;.tr {display: inline-flex;min-width: 100%;border-bottom: 1px solid #a7bfda;&:nth-child(2n) {background-color: #d1dfec;}.th {font-weight: bold;}.th,.td {display: inline-block;padding: 10px 15px;box-sizing: border-box;flex-grow: 1;font-size: 14px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}}}
使用方式
HTML
<my-table :columns="tableColumns" :data="tableData"></my-table>
JS
import MyTable from '../components/table'export default {components: {MyTable},data() {return {tableColumns: [{title: 'Name',key: 'name',width: 120},{title: 'Age',key: 'age',textAlign: 'right',render(val) {if (val >= 18) {return "<span style='color:green'>" + val + '</span>'} else {return "<span style='color:red'>" + val + '</span>'}}},{title: 'Address',key: 'address',width: 250}],tableData: [{name: 'John Brown',age: 14,address: 'New York No. 1 Lake Park',date: '2016-10-03'},{name: 'Jim Green',age: 24,address: 'London No. 1 Lake Park',date: '2016-10-01'},{name: 'Joe Black',age: 30,address: 'Sydney No. 1 Lake Park',date: '2016-10-02'},{name: 'Jon Snow',age: 17,address: 'Ottawa No. 2 Lake Park',date: '2016-10-04'}]}}}