vue+element-ui实现表格嵌套
vue+element-ui实现表格嵌套
公司的项目有表格嵌套的需求,网上找了下没有太满意的案例,然后自己看了下 element-ui 的表格 里面有一个 ‘展开行’ 的功能,然后就顺藤摸瓜,写出了一个表格嵌套的功能码
效果图
html片段
<el-table border :data="tableData" @expand-change="expandSelect" @row-click="clickRow" style="width: 100%">
<el-table-column type="expand">
<template slot-scope="props">
<el-table border :data="props.row.tableData2" style="width: 100%" @row-click="clickRow">
<el-table-column label="商品 ID" prop="id"></el-table-column>
<el-table-column label="商品名称" prop="name"></el-table-column>
<el-table-column label="描述" prop="desc"></el-table-column>
</el-table>
</template>
</el-table-column>
<el-table-column label="商品 ID" prop="id"></el-table-column>
<el-table-column label="商品名称" prop="name"></el-table-column>
<el-table-column label="描述" prop="desc"></el-table-column>
</el-table>
里面的参数可以去 element-ui 官网看看
js片段
export default {
name: "HelloWorld",
data() {
return {
tableData: [
{
id: "12987122",
name: "好滋好味鸡蛋仔",
category: "江浙小吃、小吃零食",
desc: "荷兰优质淡奶,奶香浓而不腻",
address: "上海市普陀区真北路",
shop: "王小虎夫妻店",
shopId: "10333"
},
{
id: "12987123",
name: "好滋好味鸡蛋仔",
category: "江浙小吃、小吃零食",
desc: "荷兰优质淡奶,奶香浓而不腻",
address: "上海市普陀区真北路",
shop: "王小虎夫妻店",
shopId: "10333"
},
{
id: "12987125",
name: "好滋好味鸡蛋仔",
category: "江浙小吃、小吃零食",
desc: "荷兰优质淡奶,奶香浓而不腻",
address: "上海市普陀区真北路",
shop: "王小虎夫妻店",
shopId: "10333"
},
{
id: "12987126",
name: "好滋好味鸡蛋仔",
category: "江浙小吃、小吃零食",
desc: "荷兰优质淡奶,奶香浓而不腻",
address: "上海市普陀区真北路",
shop: "王小虎夫妻店",
shopId: "10333"
}
]
};
},
methods: {
expandSelect(row, expandedRows) {
// expandedRows.length != 0 ? console.log(row.id) : ''
if(expandedRows.length != 0){
row.tableData2 = [{
id: row.id,
name: "好滋好味鸡蛋仔",
category: "江浙小吃、小吃零食",
desc: "荷兰优质淡奶,奶香浓而不腻",
address: "上海市普陀区真北路",
shop: "王小虎夫妻店",
shopId: "10333"
}]
}
},
clickRow (row, column, event) {
console.log(row.id)
// console.log(column)
// console.log(event)
}
}
};
这里说一下我的思路,在 el-table-column
里面的 template
里再放一个表格。我想点击表格左边下拉按钮再请求,所以用 expand-change
来监听,方法里传两个参数,row
(数据列) 跟expandedRows
(展开时有数组长度,闭合时为空数组,所以用它来判断来渲染数据,然后往方法里面的 row
添加一个数组进去 tableData2
这是嵌套表格的数据,然后嵌套的表格的 :data 用props.row.tableData2
就可以取到数据了)
由于我写的假数据,所以嵌套表格的id 我用外层表格的 id 来模拟请求数据
css片段
.demo-table-expand {
font-size: 0;
}
.demo-table-expand label {
width: 90px;
color: #99a9bf;
}
.demo-table-expand .el-form-item {
margin-right: 0;
margin-bottom: 0;
width: 50%;
}