Fork me on GitHub

使用ul简单模拟一个在移动端上使用的Vue表格组件

感觉手动设置 table 样式挺恶心的,而且性能也很烂,今天用 ul + flexbox 简单模拟一个 vue 上用的

my-table.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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">
<li
class="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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
export default {
props: {
columns: {
type: Array,
default() {
return []
}
},
data: {
type: Array,
default() {
return []
}
}
},
methods: {
styles(item) {
let { width, textAlign } = item
return {
width: (width || 100) + 'px',
textAlign: textAlign || 'left'
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
.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;
}
}
}

使用方式

1
<my-table :columns="tableColumns" :data="tableData"></my-table>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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'
}
]
}
}
}