官网的写法是el-table-column下面嵌套el-table-column,如下:
<template>
<el-table
:data="tableData3"
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="150">
</el-table-column>
<el-table-column label="配送信息">
<el-table-column
prop="name"
label="姓名"
width="120">
</el-table-column>
<el-table-column label="地址">
<el-table-column
prop="province"
label="省份"
width="120">
</el-table-column>
<el-table-column
prop="city"
label="市区"
width="120">
</el-table-column>
<el-table-column
prop="address"
label="地址"
width="300">
</el-table-column>
<el-table-column
prop="zip"
label="邮编"
width="120">
</el-table-column>
</el-table-column>
</el-table-column>
</el-table>
</template>
可以看出代码繁琐,重复量比较大,所以改造简单封装了下
将el-table和el-table-column独立出来
el-table封装如下:
MyTable.vue
<template>
<div class="my-table">
<el-table :data="data">
<my-column v-for="(item,index) in col" :key="index" :col="item"></my-column>
</el-table>
</div>
</template>
<script>
import MyColumn from './MyColumn'
export default {
components: {
MyColumn
},
props: {
col: {
type: Array
},
data: {
type: Array
}
}
}
</script>
<style scoped>
</style>
el-table-column封装如下:
MyColumn.vue
<template>
<el-table-column :prop="col.prop"
:label="col.label"
align="left">
<template v-if="col.children">
<my-column v-for="(item, index) in col.children"
:key="index"
:col="item"></my-column>
</template>
</el-table-column>
</template>
<script>
export default {
name: 'MyColumn',
props: {
col: {
type: Object
}
}
}
</script>
<style scoped>
</style>
使用
<template>
<div>
<my-table :col="col"
:data="data">
</my-table>
</div>
</template>
<script>
import MyTable from './MyTable'
export default {
components: {
MyTable
},
data() {
return {
col: [
{
prop: 'date',
label: '日期'
},
{
label: '配送信息',
children: [
{
prop: 'name',
label: '姓名'
},
{
label: '地址',
children: [
{
prop: 'province',
label: '省份'
},
{
prop: 'city',
label: '市区'
},
{
prop: 'address',
label: '地址'
}
]
}
]
}
],
data: [
{
date: '2016-05-03',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
},
{
date: '2016-05-02',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}
]
}
}
}
</script>
<style>
</style>
效果图
简单封装后可以动态无限级生成嵌套的表头,唯一的一个不好的地方就是自定义模版无法用这种形式自定义模版了,不过可以用render+JSX解决,问题不大
<template slot-scope="scope">
</template>