vue实现动态控制el-table表格列的展示与隐藏
1.引入el-table组件,这里我直接用官网的示例代码<template><div class="page"><el-popover width="60" trigger="click"><el-checkbox-group v-model="columnSelecteds"><el-checkbox v-for="item in colum
·
1.引入el-table组件,这里我直接用官网的示例代码
<template>
<div class="page">
<el-popover width="60" trigger="click">
<el-checkbox-group v-model="columnSelecteds">
<el-checkbox v-for="item in columnHeaders" :label="item.title" :key="item.title" ></el-checkbox>
</el-checkbox-group>
<el-button slot="reference" icon="el-icon-more" circle style="margin-left: 100px;"></el-button>
</el-popover>
<el-table
:data="tableData"
ref="dataTable"
stripe
style="width: 100%">
<el-table-column v-if="columnHeaders[0].isShow" prop="date" label="日期"></el-table-column>
<el-table-column v-if="columnHeaders[1].isShow" prop="name" label="姓名"></el-table-column>
<el-table-column v-if="columnHeaders[2].isShow" prop="address" label="地址"></el-table-column>
</el-table>
</div>
</template>
页面效果图:
2.数据绑定与监听
<script>
export default {
name: 'ElTableTest',
data() {
return {
// 表格数据
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 弄'
}],
//表头信息
columnHeaders: [
{index: 0, title: "日期", isShow: true},
{index: 1, title: "姓名", isShow: true},
{index: 2, title: "地址", isShow: true}
],
//已选择的项
columnSelecteds: ["日期","姓名", "地址"]
}
},
watch: {
/**
* @title 监听列显示隐藏
*/
columnSelecteds(newArrayVal) {
// 计算为被选中的列标题数组
var nonSelecteds = this.columnHeaders
.filter(item => newArrayVal.indexOf(item.title) == -1)
.map(item => item.title)
// 根据计算结果进行表格重绘
this.columnHeaders.filter(item => {
let isNonSelected = nonSelecteds.indexOf(item.title) != -1
if (isNonSelected) {
// 隐藏未选中的列
item.isShow = false
this.$nextTick(() => {
this.$refs.dataTable.doLayout()
})
} else {
// 显示已选中的列
item.isShow = true
this.$nextTick(() => {
this.$refs.dataTable.doLayout()
})
}
})
}
}
}
</script>
监听到已选择和未选择的列,调用doLayout()方法对表格进行重绘。
最终效果:
更多推荐
已为社区贡献5条内容
所有评论(0)