本文主要是介绍el-table 封装表格(完整代码-实时更新),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最新更新时间: 2024年9月6号
1. 添加行内编辑、表头搜索
<template><!-- 简单表格、多层表头、页码、没有合并列行 --><div class="maintenPublictable"element-loading-background="rgba(255,255,255,0.5)"><!--cell-style 改变某一列行的背景色 --><!-- tree-props 配置树形子表row-click: 某一行单击事件highlight-current-row:高亮选中某行default-expand-all:默认是否展开字列表current-change:管理选中时触发的事件selection-change:多选框row-key="id": id:一定要跟后台返回来的id一致,不一致,会出错show-summary: 显示合计summary-method: 合计指定的某一列row-dblclick: 某一行被双击:row-class-name="tableRowClassName" :行样式stripe :斑马纹bordershow-overflow-tooltip :=true(默认是true) 当内容过长被隐藏时,会在hover时以tooltip的形式显示出来.若=false,那么数据就可以换行展示.[可以设置为动态改变]--><!-- :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" stripe--><el-tablestyle="background: transparent !important"borderclass="rollTableRow"ref="table":data="tableData":height="heights":show-summary="showSum":summary-method="getSummaries"@selection-change="handleSelectionChange":key="itemKey":cell-style="tableCellStyle"@row-click="clickRow"@row-dblclick="rowDblclick"row-key="ID":default-expand-all="defaultall":highlight-current-row="highlightCurrent"@current-change="handleCurrentChangeRow":tree-props="{ children: 'Children' }"header-row-class-name="headerStyle"v-loading="loading"element-loading-text="拼命加载中":element-loading-svg="svg":header-cell-style="{ background: '#f8f8f9' }"><el-table-column type="selection"v-if="isSelection"width="55"></el-table-column><el-table-columntype="index" v-if="isIDx"width="80"align='center'label="序号"></el-table-column><templatev-for="(item, index) in tableHeader"><!-- 1. 这是第一层 --><!-- sortable: 排序 item.direction; item.direction 方向,判断居中还是靠右 --><el-table-columnv-if="!item.child":key="index":prop="item.prop":label="item.label"header-align="center":align="item.align || 'center'":min-width="item.width":sortable="item.sortable"show-overflow-tooltip><!-- 新增插槽,用于表头添加搜索; visible=true popover组件展示, @keydown.enter 回车事件, titleSelectinput 搜索值--><template #header >{{item.label}}<el-popover :visible="item.visible" placement="top" :width="160" :ref="`popover-${index}`" v-if="item.label=='操作类型'"><el-input v-model="titleSelectinput" placeholder="请输入搜索条件" @keydown.enter="changeData($event,index,item)"/><template #reference><el-button circle class="buttonIcon"><el-icon @click="Ones(item,index)"><Search /></el-icon></el-button></template></el-popover> </template><!-- 用于行内编辑,前提是每条数据中必须有show字段,若show=true,当前行为编辑状态 --><template #default="scope"><el-input v-if="scope.row.show" v-model="scope.row[item.prop]" @keyup.enter="saveEdit(scope.$index, scope.row)" placeholder="请输入内容"> </el-input> <span v-else> {{ scope.row[item.prop] }} </span> </template></el-table-column><!-- 二级表头 --><el-table-column v-else:key="index + 1":prop="item.prop":label="item.label":type="item.type":align="item.align || 'center'"><templatev-for="(childItem, index) in item.child"><!-- 三级表头 --><el-table-columnv-if="!childItem.child":key="index":prop="childItem.prop":label="childItem.label"header-align="center":align="childItem.center":min-width="childItem.width"></el-table-column><el-table-column v-else:key="index + 1":prop="childItem.prop":label="childItem.label":type="childItem.type":align="childItem.align || 'center'"><templatev-for="(childItem, index) in item.child"><!-- 这是第三层 --><el-table-columnv-if="!childItem.child":key="index":prop="childItem.prop":label="childItem.label"header-align="center":align="childItem.center":min-width="childItem.width"></el-table-column><el-table-column v-else:key="index + 1":prop="childItem.prop":label="childItem.label":type="childItem.type":align="childItem.align || 'center'"></el-table-column></template></el-table-column></template></el-table-column></template><!-- 表格最后一列是否是勾选框【完成情况】 --><el-table-column v-if="isSelect"align="center"><!-- slot="header" 替换成=>#header; slot-scope="scope"替换成=>#default="scope"--><template #header><el-checkbox @change="allCheck(isAllcheck, tableData, ClickIdsList, isIndeterminate)"size="large"v-model="isAllcheck":indeterminate="isIndeterminate"></el-checkbox>完成情况</template><template #default="scope"><el-checkbox@change="OnesClick(scope.row)"v-model="scope.row.check"class="ml-4"size="large"></el-checkbox></template></el-table-column><!-- 容量空间占比 1--><el-table-columnv-if="isSplaceShow"align="center"label="存储容量占比"><template #default="scope"><el-progress:text-inside="true":stroke-width="26":percentage="scope.row.one"></el-progress>{{ scope.row.one }}/{{ scope.row.two }}</template></el-table-column><!-- 空间占比 1.1--><el-table-columnv-if="isSplaceShow && isJueseRong"align="center"label="操作列"><template #default="scope"><!-- handleEdit(scope.$index, scope.row) --><el-button@click="spaceFenpei(scope.$index, scope.row)">容量分配(Gb)</el-button></template></el-table-column><!-- 是否启用--><el-table-column v-if="isSwitch"align="center"label="是否启用"><template #default="scope"><!-- handleEdit(scope.$index, scope.row) --><el-switchv-model="scope.row.switchValue"active-color="#13ce66"inactive-color="#ff4949"@change="switchChange(scope.row)"></el-switch></template></el-table-column><!-- 查看权限--><el-table-column v-if="isCaozuo"align="center"label="操作列"><template #default="scope"><!-- handleEdit(scope.$index, scope.row) --><el-button@click="caozuoBtn(scope.$index, scope.row)">查看权限</el-button></template></el-table-column><!-- 查看详情 --><el-table-column v-if="isLook"align="center"label="查看详情"><template #default="scope"><el-button@click="isLookBtn(scope.$index, scope.row)">查看详情</el-button></template></el-table-column><el-table-column v-if="isanewBtn"align="center"label="重试"><template #default="scope"><el-buttonv-show="scope.row.success == '1' ? true : false"@click="anewBtn(scope.$index, scope.row)"type="text">重试</el-button></template></el-table-column><!-- 操作日志 查看详情 --><el-table-column v-if="usertime5"align="center"label="操作"width="200"><template #default="scope"><el-button@click="isLookBtn(scope.$index, scope.row)">详情</el-button><el-button@click="isLookBtn1(scope.$index, scope.row)">重试</el-button></template></el-table-column><!-- 编辑+删除 --><el-table-column v-if="isUpdataDel"align="center"label="操作"width="200"><template #default="scope"><el-button@click="UpdataclickDel(scope.$index, scope.row)">编辑</el-button><el-button@click="UpdataclickDel(scope.$index, scope.row)">删除</el-button></template></el-table-column></el-table><!-- 分页 --><div v-if="showFenYe"class="fenYeStyle"><el-pagination@size-change="handleSizeChange"@current-change="handleCurrentChange":current-page="page.currentPage":page-sizes="[5, 10, 15, 20]":page-size="page.pagesize"layout="total, sizes, prev, pager, next, jumper":total="page.total"></el-pagination></div></div>
</template>
<script>
// import preventBack from "vue-prevent-browser-back"; //阻止返回
import { PublicFunction } from "@/utils/vuePublic"
import { ClickOutside as vClickOutside } from "element-plus";
export default {name: "maintenPublictable",components: {},props: {// 接收的是:是否有分页、是否有勾选columns: {type: Object,default: {},},// 接收的是:页码pagination: {type: Object,default: {},},},data () {return {titleSelectinput:"",//记录表头搜索值visible:false,//popover弹出框tableHeader: [], //表头tableData: [], //数据itemKey: "",types: 1, //用于合并,判断是否需要合并//#region 与父组件关联heights: 1,getHeight: 20, //高度isSelect: false, //勾选框isSplaceShow: false, //容量占比isCaozuo: false, //操作列isLook: false, //查看详情isanewBtn: false, //重试showFenYe: false, //是否有分页isSelection: false, //是否有多选框isIDx:false,//是否显示前面的序号isTag: false, //是否有标签defaultall: false, //是否默认展开所有行(用于有树状结构的表格)highlightCurrent: false, //高亮选中showSum: false, //合计//#endregion// 页码page: {currentPage: 1, //当前页pagesize: 10, //当前页的条数total: 20, //总数},//多选框multipleSelection: [],//#region 用于右侧的完成情况//选择isAllcheck: false, //全选ClickIdsList: [], //已选择集合组isIndeterminate: false, //部分选中,默认是false//#endregionloading: false,flag: 1,//操作列:容量分配功能 显示隐藏isJueseRong: true,//敏感词启用禁用isSwitch: false,// 操作日志usertime5: false,isUpdataDel:false,//操作列-【编辑+删除】}},// mixins: [preventBack], //注入 阻止返回上一页created () {// this.heights = window.innerHeight - 200;},watch: {// 监听对象的写法(监听页码的变化)pagination: {handler (newValue, oldVal) {this.page.total = newValue.total},deep: true, // 深度监听// immediate: true, //写上它,初始化时也会调用监听},},mounted () {this.$nextTick(() => {if (this.$refs.table != null) {this.$refs.table.$el.getBoundingClientRect().top //表格距离浏览器的高度let heightswitch (this.flag) {case 1:height = 0breakcase 2:height = 80breakcase 3:height = 110breakcase 4:height = -65breakcase 7:height = 90breakcase 8:height = -30breakcase 9:height = 160breakdefault:break}// 根据浏览器高度设置初始高度this.heights =window.innerHeight - this.$refs.table.$el.offsetTop - 270 - height// 监听浏览器高度变化,修改表格高度window.onresize = () => {this.heights =window.innerHeight - this.$refs.table.$el.offsetTop - 270 - height}}})this.init()},methods: {//#region 动态更改行颜色tableRowClassName({row, rowIndex}) {if (rowIndex === 1) {return 'warning-row'; //warning-row 类名} else if (rowIndex === 3) {return 'success-row';}return '';},//#endregion//#region 行内编辑/** 操作列-》实现行内编辑* index:索引;row:当行数据*/UpdataclickDel(index,row) {this.tableData[index] = { ...row, show: true }; //更新数组中的某个元素},/*** 用于行内编辑的回车事件*/saveEdit(index,row){this.tableData[index] = { ...row, show: false }; //更新数组中的某个元素console.log(this.tableData[index],'获取修改之后的值并调用编辑的接口');},
//#endregion//#region 表头添加搜索插槽 /*** 表头icon的点击事件*/Ones (val,index) {this.tableHeader[index].visible=!this.tableHeader[index].visible},/*** 回车事件*/changeData(event,index,item) {if (!event.ctrlKey) {// 如果没有按下组合键ctrl,则会阻止默认事件event.preventDefault();this.test(index,item);} else {// 如果同时按下ctrl+回车键,则会换行this.orderInfo += '\n';}},/*** 实际上就是 按回车键,将搜索条件存下来,调用方法*/test(index,item){// console.log('触发了回车事件,并且没有换行喔~');this.tableHeader[index].visible=!this.tableHeader[index].visiblelet query1=item.proplet query2=this.titleSelectinputlet param = {}; //使用方括号语法动态设置对象的键 param[query1] = query2; console.log(param,'获取输入的条件',this.titleSelectinput);},//#endregion//在父组件初始化时,需要获得页码,所以子组件初始化时把页码传过去init () {let _this = this_this.getHeight = this.columns.getHeight_this.showSum = this.columns.showSum //合计_this.defaultall = this.columns.defaultall //是否展开所有行_this.isSelect = this.columns.isSelect //右侧的完成情况_this.isSplaceShow = this.columns.isSplaceShow //容量占比_this.isCaozuo = this.columns.isCaozuo //容量占比_this.isLook = this.columns.isLook //查看详情_this.isanewBtn = this.columns.isanewBtn //重试_this.isTag = this.columns.isTag //是否有标签_this.usertime5 = this.columns.usertime5 //是否有标签_this.isUpdataDel = this.columns.isUpdataDel //是否展示【编辑+删除】_this.showFenYe = this.columns.showFenYe_this.isSelection = this.columns.isSelection //左侧的多选框_this.isIDx = this.columns.isIDx //是否显示前面的序号_this.highlightCurrent = this.columns.highlightCurrent //高亮选中_this.page.total = this.pagination.total_this.$emit("getPage", {data: {pageSize: _this.page.pagesize,pageNum: _this.page.currentPage,isTypes: 1,},})this.SetDataTableHeader()},//#region 页码//一页有多少条数据handleSizeChange (val) {let _this = this_this.page.pagesize = val// 子传父_this.$emit("getPage", {data: {pageSize: _this.page.pagesize,pageNum: _this.page.currentPage,isTypes: 2,},})},//第几页/切换页码handleCurrentChange (val) {let _this = this_this.page.currentPage = val_this.$emit("getPage", {data: {pageSize: _this.page.pagesize,pageNum: _this.page.currentPage,isTypes: 2,},})},//#endregion/**表头赋值* @param GetDataLists 表头* @param flag 用于动态更改table高度*/SetDataTableHeader (GetDataLists, flag) {//重新渲染,itemKey用于处理Table不渲染的问题this.itemKey = Math.random()this.flag = flag ? flag : this.flag//重新渲染数据表this.tableHeader = GetDataLists},//table值SettableData (tabledata) {console.log(tabledata, "数据威慑")let _this = thisthis.itemKey = Math.random()_this.tableData = tabledata},//左侧:多选框handleSelectionChange (val) {console.log(val, "handleSelectionChange")this.multipleSelection = valthis.$emit("handleSelectionChange", val)},//#region 插槽/*** 容量分配*/spaceFenpei (index, val) {this.$emit("handlespaceFenpei", val)},/*** 操作列*/caozuoBtn (index, val) {this.$emit("handlecaozuoBtn", val)},/*** 查看详情*/isLookBtn (index, val) {this.$emit("handleisLookBtn", val)},/*** 查看详情*/isLookBtn1 (index, val) {this.$emit("handleisLookBtn1", val)},/*** 接入中心---重试*/anewBtn (index, val) {this.$emit("handleanewBtnBtn", val)},// 是否启用---切换开关的时候switchChange (val) {this.$emit("getchangeswicth", val)},//#endregion//#region 下面这个是用于最右侧的完成情况//全选 调取公共js文件的方法allCheck (isAll, tableData, checkList, isCheck) {//接收传过来的值let objData = PublicFunction.allCheck(isAll,tableData,checkList,isCheck)this.isAllcheck = objData.isAllthis.ClickIdsList = objData.checkList},//单行选择OnesClick (rows) {if (rows.check) {this.ClickIdsList.push(rows.id)} else {let index = this.ClickIdsList.indexOf(rows.id)this.ClickIdsList.splice(index, 1)}this.isIndeterminate =this.ClickIdsList.length > 0 &&this.ClickIdsList.length < this.tableData.lengththis.isAllcheck = this.ClickIdsList.length == this.tableData.length},//#endregion// 合并单元格objectSpanMethod ({ row, column, rowIndex, columnIndex }, tableData, types) {if (types === 1) {switch (columnIndex // 将列索引作为判断值) {// 通过传递不同的列索引和需要合并的属性名,可以实现不同列的合并(索引0,1 指的是页面上的0,1)case 2:return PublicFunction.MergeCol(tableData, "itemDetail", rowIndex)case 1:return PublicFunction.MergeCol(tableData, "item", rowIndex)}} else {//保障作业switch (columnIndex) {case 1:return PublicFunction.MergeCol(tableData, "item", rowIndex)}}//判断检查内容是否为空// if (// tableData[columnIndex].checkContent != undefined ||// tableData[columnIndex].checkContent != null// ) {// } else {// }},// 提交(在父组件点击提交时调用这个方法)childSumbit () {let param = {tabledata: this.tableData,ClickIdsList: this.ClickIdsList,multipleSelection: this.multipleSelection,}// 把值传给父组件this.$emit("sumbitData", param)},//#region 点击事件整合//行点击事件clickRow (row, column, event) {this.$emit("rowClick", row)this.toggleSelection(row) //如果前面有多选框,则单击时多选框也勾选console.log('单击行事件',val);},//某一行被双击rowDblclick (row, column, event) {this.$emit("rowDoubleClick", row)},// 行选中事件handleCurrentChangeRow (val) {this.$emit("handleCurrentChangeRow", val)},//#region 单击某一行,该行多选框显示已选中/*** 单击某一行,该行多选框显示已选中*/toggleSelection (rows) {if (rows) {// rows.forEach((row) => {// this.$refs.table.toggleRowSelection(row);// });this.$refs.table.toggleRowSelection(rows)} else {this.$refs.table.clearSelection()}},toggleRowSelection (val) {this.$nextTick(() => {this.$refs.table.toggleRowSelection(val, true)})},//#endregion//#endregion// 改变某一列的行的背景色tableCellStyle ({ row, column, rowIndex, columnIndex }) {//如果是第一列// if (columnIndex === 1) {// //如果这一行的字段==未维护// if (row.state == "未维护") {// // 如果是未维护——背景色浅蓝色,字体色蓝色;// return "background:#ecf5ff; color:#409eff";// } else if (row.state == "已维护") {// // 如果是已维护——背景色绿色,字体色白色;// return "background:#67c23aa6;color:#fff ";// } else if (row.state == "部分维护") {// // 如果是已维护——背景色棕色,字体色白色;// return "background:#e6a23cab;color:#fff ";// } else {// }// } else {if (row.EliminateTime < 24 && columnIndex === 7) {return { color: "red" }}},// 取消选择setCurrent () {this.$refs.table.setCurrentRow()},// 合计 指定某一列添加合计getSummaries (param) {const { columns, data } = paramconst sums = []columns.forEach((column, index) => {if (index === 0) {sums[index] = "合计"return} else if (column.property == "Amount") {//如果是经费(正常的加减法)const values = data.map((item) => Number(item[column.property]))if (!values.every((value) => isNaN(value))) {sums[index] = values.reduce((prev, curr) => {const value = Number(curr)var sum = 0if (!isNaN(value)) {sum = Number(Number(prev) + Number(curr)).toFixed(2)return sum} else {return prev}}, 0)sums[index] += " "}}})return sums},},//#endregion
};
</script><style scoped lang='scss'>
.maintenPublictable {background: #fff;
}
// 表土icon样式
.buttonIcon{background-color: transparent;border-color: transparent;padding-left: 0;}
//表头icon 样式::v-deep .el-button:focus-visible {outline: 2px solid #fdfdfd;
}
/*!* 表格表头 *!*/
/*.maintenPublictable ::v-deep .el-table th,*/
/*::v-deep .el-table thead.is-group th.el-table__cell {*/
/* !* background: linear-gradient(147deg, #70c0ff, #2f9fff); *!*/
/* !* background: transparent; *!*/
/* background: #295d85;*/
/* color: #fff;*/
/* padding: 0;*/
/* margin: 0;*/
/* height: 3rem !important;*/
/*}*//*!*****滚动条影藏 *!*//*::v-deep .el-table--scrollable-y ::-webkit-scrollbar {*/
/* display: none !important;*/
/*}*//*!**lable名字 *!*/
/*::v-deep .el-checkbox__label {*/
/* color: #fff;*/
/*}*//*!* 背景透明 *!*/
/*::v-deep .el-table tr {*/
/* background-color: transparent;*/
/* color: #fff;*/
/*}*//*!* 表格背景透明 *!*/
/*.rollTableRow {*/
/* background: transparent;*/
/* !* border边框 *!*/
/* --el-table-border-color: transparent;*/
/*}*//*!* 表格背景图 *!*/
/*.maintenPublictable {*/
/* !*background: url("@/assets/imgList/tableBG.png") no-repeat;*!*/
/* background-size: 100% 100%;*/
/* padding: 4%;*/
/*}*//*!* 鼠标悬浮时 表格背景色及字体颜色 *!*/
/*::v-deep .el-table tbody tr:hover > td {*/
/* background-color: rgb(65, 111, 180) !important;*/
/* color: #ffffff;*/
/*}*//*!* 斑马线颜色 *!*/
/*::v-deep*/
/* .el-table--striped*/
/* .el-table__body*/
/* tr.el-table__row--striped*/
/* td.el-table__cell {*/
/* background: #295d85;*/
/*}*//*!* 箭头 *!*/
/*::v-deep .el-table__expand-icon > .el-icon {*/
/* color: #f3f3f3;*/
/*}*/
</style><style scoped>
/*!* 页码 *!*/
/*::v-deep .el-pagination__total,*/
/*::v-deep .el-pagination__jump {*/
/* color: #f3f3f3;*/
/*}*//*::v-deep .el-select .el-input__wrapper {*/
/* cursor: pointer;*/
/* background-color: #418de7;*/
/* border: none;*/
/* box-shadow: none;*/
/*}*//*::v-deep .el-select .el-input__inner {*/
/* cursor: pointer;*/
/* color: #f3f3f3;*/
/*}*//*::v-deep .el-pager li.is-active {*/
/* color: #f3f3f3;*/
/* cursor: default;*/
/* font-weight: 700;*/
/* background-color: #418de7;*/
/*}*//*!* 箭头按钮 *!*/
/*::v-deep .el-input__wrapper,*/
/*::v-deep .el-pagination button:disabled,*/
/*::v-deep .el-pagination button,*/
/*::v-deep .btn-next {*/
/* background-color: #418de7;*/
/* box-shadow: none;*/
/* color: #f3f3f3;*/
/*}*/::v-deep .el-pagination {margin-top: 10px !important;
}/*::v-deep .el-pager li.is-active,*/
/*::v-deep .el-pager li {*/
/* background-color: #418de7;*/
/* color: #f3f3f3;*/
/*}*/
.maintenPublictable {background: transparent !important;
}
/*!*最外层透明*!*/
.maintenPublictable .el-table,
.el-table__expanded-cell {border: none !important;
}
/*!* 表格内背景颜色 *!*/
/* ::v-deep .el-table th,
::v-deep .el-table tr,
::v-deep .el-table td {background-color: transparent;
} */
/* ::v-deep .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf {border-bottom: 0 !important;
} */
/* a5c4f7 */
::v-deep .el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {/* line-height: 3rem; */font-size: 16px;
}/*!* 鼠标悬浮时 表格背景色及字体颜色 *!*/
/* ::v-deep .el-table tbody tr:hover > td {background-color: rgb(91, 179, 254) !important;color: #ffffff;
} */
/* 高亮的颜色 */
/* ::v-deep .el-table__body tr.current-row>td.el-table__cell {background-color: #5296ff;} */
::v-deep .el-pagination {justify-content: flex-end;
}
</style>
PS:此代码仅用于记录。
这篇关于el-table 封装表格(完整代码-实时更新)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!