使用elemenui树形删除数据的时候刷新页面,我在网上找了好多方法,要么没用,要么都是部分代码,自己又看不懂,不得不硬着头皮看源码,发现了有个方法可以刷新。
使用elemenui树形删除数据的时候刷新页面。源码里有一个判断,如果刷新的数据等于空,那么不执行刷新方法。所以我们直接使用resolve()来刷新是行不通的。
我在网上找了好多方法,要么没用,要么都是部分代码,自己又看不懂,不得不硬着头皮看源码,发现了有个方法可以刷新。可以从res中获取数据,再把数据清空掉即可
主要代码
return {//不知道为什么lazyTreeNodeMap要写在states里边,有时间再研究states: {lazyTreeNodeMap: {},},
}
//如果是空数组,进入这个单独处理删除的方法
if (!dataArray1.length){
//把当前lazyTreeNodeMap节点的tree替换成 空数组(清空)
this.$set(this.$refs.multipleTable.store.states.lazyTreeNodeMap,tree,{})
//也可以写成dataArray1,因为dataArray1就是空的
//this.$set(this.$refs.multipleTable.store.states.lazyTreeNodeMap,tree,dataArray1)
}
完整代码
<template><div class="app-container"><div class="selfSearch" ref="selfSearch"><div class="search_left"><query :params.sync="queryParams" keywordParams="pr_name,is_entity" @finishCommit="getList"><el-form slot="form" class="seniorQuery" :model="queryParams" ref="queryForm" size="small" :inline="true"v-show="showSearch" label-width="110px"><el-form-item label="编目清单名称" prop="prName"><el-inputv-model="queryParams.prName"placeholder="请输入编目清单名称"clearable@keyup.enter.native="handleQuery"/></el-form-item></el-form></query></div><div class="search_right"><!-- <el-checkbox v-model="queryParams.queryChecked" label="显示全部" border @change="checkedChange"></el-checkbox>--><el-buttontype="primary"icon="el-icon-plus"size="small"@click="handleAdd"v-hasPermi="['ba:baConserveBoq:add']">新增</el-button><right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar></div></div><!-- <el-table v-if="refreshTable":data="baConserveBoqList"row-key="id":default-expand-all="isExpandAll"style="width: 100%; margin-bottom: 20px;"borderlazy:select-on-indeterminate="true":load="load"@sort-change="sortChange"@select="select"@select-all="selectAll"@selection-change="selectionChange" ref="multipleTable":tree-props="{ children: 'children', hasChildren: 'hasChildren' }":height="selfHeight" stripe></el-table>--><el-table:data="tableData1"row-key="id":default-expand-all="isExpandAll"style="width: 100%; margin-bottom: 20px;"borderlazy:load="load1":select-on-indeterminate="true"@sort-change="sortChange"@select="select"@select-all="selectAll"@selection-change="selectionChange" ref="multipleTable":height="selfHeight":tree-props="{ children: 'children', hasChildren: 'hasChildren' }"><el-table-column type="selection" width="55" align="center"/><el-table-column sortable label="编目清单编码" align="left" prop="prCode"/><el-table-column sortable label="编目清单名称" align="center" prop="prName"/><el-table-column sortable label="单价" align="center" prop="price"/><el-table-column sortable label="计量单位" align="center" prop="measuringUnit"/><el-table-column sortable label="显示顺序" align="center" prop="num"/><el-table-column sortable label="层级" align="center" prop="prLevel"><template slot-scope="scope"><dict-tag :options="dict.type.ba_boq_pr_level" :value="scope.row.prLevel"/></template></el-table-column><el-table-column sortable label="创建时间" align="center" prop="createTime" width="200"><template slot-scope="scope"><span>{{ parseTime(scope.row.createTime) }}</span></template></el-table-column><el-table-column sortable label="状态" align="left" prop="status" width="150"><template slot-scope="scope"><template v-if="scope.row.status === '0'"><el-tag type="success">正常</el-tag></template><template v-else-if="scope.row.status === '1'"><el-tag type="danger">禁用</el-tag></template></template></el-table-column><!-- width="240" align="center"class-name="small-padding fixed-width" fixed="right" --><el-table-column width="240" label="操作" align="center" class-name="small-padding fixed-width"><template slot-scope="scope"><el-buttonsize="small"type="text"icon="el-icon-edit"@click="handleUpdate(scope.row)"v-hasPermi="['ba:baConserveBoq:edit']">修改</el-button><el-buttonsize="small"type="text"icon="el-icon-plus"@click="handleAdd(scope.row)"v-hasPermi="['ba:baConserveBoq:add']">添加下级</el-button><el-buttonv-if="scope.row.parentId != 0"size="small"type="text"icon="el-icon-delete"@click="handleDelete(scope.row)"v-hasPermi="['ba:baConserveBoq:remove']">删除</el-button></template></el-table-column></el-table><!-- 懒加载 lazy --><!-- 添加或修改养护工程量清单对话框 --><el-dialog class="spec-dialog" :title="title" :visible.sync="open" width="70%" append-to-body><el-form ref="form" :model="form" :rules="rules" label-width="150px"><el-row :gutter="24"><el-col :span="12"><el-form-item label="编目编码" prop="prCode"><el-input v-if="form.id ==null || form.id ==''" v-model="form.prCode" placeholder="请输入编目编码"/><el-input v-if="form.id !==null&& form.id !==''" v-model="form.prCode"placeholder="请输入编目编码"/></el-form-item></el-col><el-col :span="12"><el-form-item label="编目名称" prop="prName"><el-input v-model="form.prName" placeholder="请输入编目名称"/></el-form-item></el-col></el-row><el-row :gutter="24"><el-col :span="12"><el-form-item label="单价" prop="price"><el-input v-model="form.price" placeholder="请输入单价"/></el-form-item></el-col><el-col :span="12"><el-form-item label="计量单位" prop="measuringUnit"><el-input v-model="form.measuringUnit" placeholder="请输入计量单位"/></el-form-item></el-col></el-row><el-row :gutter="24"><el-col :span="12"><el-form-item label="层级" prop="prLevel"><el-select v-model="form.prLevel" placeholder="层级" clearable><el-optionv-for="dict in dict.type.ba_boq_pr_level":key="dict.value":label="dict.label":value="dict.value"/></el-select></el-form-item></el-col><el-col :span="12"><el-form-item label="备注" prop="remarks"><el-input v-model="form.remarks" placeholder="请输入备注"/></el-form-item></el-col></el-row><el-row :gutter="24"><el-col :span="12"><el-form-item label="状态"><el-radio-group v-model="form.status"><el-radiov-for="dict in dict.type.sys_normal_disable":key="dict.value":label="dict.value">{{ dict.label }}</el-radio></el-radio-group></el-form-item></el-col><el-col :span="12"><el-form-item label="显示排序" prop="num"><el-input-number v-model="form.num" controls-position="right" :min="0"/></el-form-item></el-col></el-row></el-form><div class="susp-btn"><el-button type="primary" @click="submitForm">保 存</el-button><el-button @click="cancel">关 闭</el-button></div></el-dialog><!-- <el-col :span="1" style="display: flex;align-items: center;justify-content: center;cursor: pointer;"><div class="folding" @click="toggleCollapse"><i v-if="showArrow" class="el-icon-caret-right"></i><i v-else class="el-icon-caret-left"></i></div></el-col><el-col :span="isCollapsed ? 0 : 6"><div class="diseaseProcess"></div></el-col>--></div>
</template><script>import {listBaConserveBoq,getBaConserveBoq,delBaConserveBoq,addBaConserveBoq,updateBaConserveBoq, selectParentIdById
} from "@/api/maintain/ba/baConserveBoq";import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import log from "@/views/monitor/job/log.vue";export default {name: "BaConserveBoq",dicts: ['sys_normal_disable', 'ba_boq_pr_level', 'ba_boq_entity'],components: {Treeselect},data() {return {states: {// defaultExpandAll 存在于 expand.js 中,这里不重复添加// 在展开行中,expandRowKeys 会被转化成 expandRows,expandRowKeys 这个属性只是记录了 TreeTable 行的展开// TODO: 拆分为独立的 TreeTable,统一用法expandRowKeys: [],treeData: {},indent: 16,lazy: false,lazyTreeNodeMap: {},lazyColumnIdentifier: 'hasChildren',childrenColumnName: 'children'},idCounter: 1,stagingArea: null,dataMap: new Map(),dataParentIdArr: [],tableData1: [],//折叠箭头showArrow: true,// 自定义折叠isCollapsed: false,// 自定义高度selfHeight: null,// 工程量编目清单树选项baboqOptions: [],// 重新渲染表格状态refreshTable: true,// 是否展开,默认全部展开isExpandAll: false,// 遮罩层loading: true,// 显示搜索条件showSearch: true,// 养护工程量清单表格数据baConserveBoqList: [],// 养护工程量清单树选项baConserveBoqOptions: [],// 弹出层标题title: "",// 是否显示弹出层open: false,// 查询参数queryParams: {measuringUnit: null,//单价price: null,//单位parentId: null,prName: null,num: null,status: null,prCode: null,prLevel: null,remarks: null,isEntity: null},// 保存 id 对应的chilren指针childMapById:new Map(),// 表单参数form: {},// 表单校验rules: {prCode: [{required: true, message: "编目编码不能为空", trigger: "blur"}],prName: [{required: true, message: "编目名称不能为空", trigger: "blur"}],isEntity: [{required: true, message: "不能为空", trigger: "blur"}],}};},created() {this.getList();},mounted() {this.getMyHeight()},methods: {filteredData() {// 过滤隐藏的数据let dataArray = [];for (let i = 0; i < this.tableData1.length; i++) {}//this.tableData1 = dataArray},load1(tree, treeNode, resolve) {console.log("第一个展开" , tree)setTimeout(() => {this.dataMap.set(tree.id, {tree,treeNode, resolve});let dataArray1 = [];for (let i = 0; i < this.baConserveBoqList.length; i++) {const item = this.baConserveBoqList[i];item.deleted = false;//通过id找父集idif (tree.id === item.parentId) {let num = 0;// 查找当前id在父集id中能匹配到数据 当前的hasChildren truefor (let j = 0; j < this.dataParentIdArr.length; j++) {const getParentId = this.dataParentIdArr[j];if (item.id === getParentId) {num = 1;}}if (num === 1) {item.hasChildren = true} else {item.hasChildren = false}dataArray1.push(item);}}resolve(dataArray1)}, 100)},async load2(tree, treeNode, resolve) {console.log("刷新")setTimeout(async () => {let dataArray1 = [];for (let i = 0; i < this.baConserveBoqList.length; i++) {const item = this.baConserveBoqList[i];item.hide = false//通过id找父集idif (tree === item.parentId) {let num = 0;for (let j = 0; j < this.dataParentIdArr.length; j++) {const getParentId = this.dataParentIdArr[j];if (item.id === getParentId) {num = 1;}}if (num === 1) {item.hasChildren = true} else {item.hasChildren = false}dataArray1.push(item);}}resolve(dataArray1)if (!dataArray1.length){this.$set(this.$refs.multipleTable.store.states.lazyTreeNodeMap,tree,dataArray1)}}, 500)},toggleCollapse() {this.isCollapsed = !this.isCollapsed;this.showArrow = !this.showArrow;},getMyHeight() {this.$nextTick(() => {let myHeight = this.$getHeight.getMyHeight(window.getComputedStyle(this.$refs.selfSearch).height)this.selfHeight = myHeight + 20})},/** 提示全部*/checkedChange(val) {this.queryParams.queryChecked = val;this.getList()},/** 查询养护工程量清单列表 */async getList() {this.$modal.loading('加载中...')await listBaConserveBoq(this.queryParams).then(response => {this.baConserveBoqList = response.data//console.log("数组长度 查询===" + this.baConserveBoqList.length)//let dataParentId = [];//保存父类idthis.dataParentIdArr = response.data.map(item=>item.parentId)//保存第一层let dataArray = [];for (let i = 0; i < response.data.length; i++) {const item = response.data[i];if (item.parentId === "0") {const isHasChildren = this.dataParentIdArr.indexOf(item.id)>-1item.hide = falseitem.hasChildren = isHasChildren;dataArray.push(item);}}this.tableData1 = dataArray;this.$modal.closeLoading()}).catch(err => {this.$modal.closeLoading()});},/** 转换养护工程量清单数据结构 */normalizer(node) {if (node.children && !node.children.length) {delete node.children;}return {id: node.id,label: node.prName,children: node.children};},/** 展开/折叠操作 */toggleExpandAll() {this.refreshTable = false;this.isExpandAll = !this.isExpandAll;this.$nextTick(() => {this.refreshTable = true;});},//排序sortChange(column) {// 可以打印一下该函数的参数就明白了// 下面的if判断根据自己的需要些我后台设置的只能识别desc与ascif (column.order === 'descending') {this.queryParams.isAsc = 'desc'} else {this.queryParams.isAsc = 'asc'}// 排序的字段传给后台this.queryParams.orderByColumn = column.prop// 传入查询参数,重新查询一次this.getList()},/** 查询部门下拉树结构 */getTreeselect() {listBaConserveBoq().then(response => {this.baConserveBoqOptions = [];const data = {id: 0, prName: '顶级节点', children: []};data.children = this.handleTree(response.data, "id", "parentId");this.baConserveBoqOptions.push(data);});},// 选中父节点时,子节点一起选中取消select(selection, row) {const hasSelect = selection.some(el => {return row.id === el.id})if (hasSelect) {if (row.children) {// 解决子组件没有被勾选到this.setChildren(row.children, true)}} else {if (row.children) {this.setChildren(row.children, false)}}},// 取消按钮cancel() {this.open = false;this.reset();},// 表单重置reset() {this.form = {id: null,parentId: null,ancestors: null,prName: null,num: null,status: "0",delFlag: null,createBy: null,createTime: null,updateBy: null,updateTime: null,prCode: null,prLevel: null,remarks: null,isEntity: null,};this.resetForm("form");},/** 搜索按钮操作 */handleQuery() {this.getList();},/** 重置按钮操作 */resetQuery() {this.resetForm("queryForm");this.handleQuery();},/** 新增按钮操作 */handleAdd(row) {this.reset();this.getTreeselect();if (row != null && row.id) {this.form.parentId = row.id;}// listBaboq().then(response => {// this.baboqOptions = [];// this.baboqOptions = this.handleTree(response.data, "id", "parentId", "children", "0")// });this.form.status = "0";this.form.isEntity = "2";this.open = true;this.title = "添加养护工程量清单";},// 选择全部selectAll(selection) {// tabledata第一层只要有在selection里面就是全选const isSelect = selection.some(el => {const tableDataIds = this.tableData.map(j => j.id)return tableDataIds.includes(el.id)})// tableDate第一层只要有不在selection里面就是全不选const isCancel = !this.tableData.every(el => {const selectIds = selection.map(j => j.id)return selectIds.includes(el.id)})if (isSelect) {selection.map(el => {if (el.children) {// 解决子组件没有被勾选到this.setChildren(el.children, true)}})}if (isCancel) {this.tableData.map(el => {if (el.children) {// 解决子组件没有被勾选到this.setChildren(el.children, false)}})}},// 获取到选中的selectionChange(selection) {this.ids = selection.map(item => item.id)this.single = selection.length !== 1this.multiple = !selection.length},/** 修改按钮操作 */handleUpdate(row) {this.reset();this.getTreeselect();getBaConserveBoq(row.id).then(response => {this.form = response.data;this.open = true;this.title = "修改养护工程量清单";});},/** 提交按钮 */async submitForm() {this.$refs["form"].validate(async valid => {if (valid) {if (this.form.price !== '' && this.form.price !== null && this.form.price !== undefined) {if (isNaN(this.form.price) || parseFloat(this.form.price) <= 0) {this.$message.error("单价数值不合法!");return; // 值不是数字、小数或正数,停止执行}}if (this.form.id != null) {console.log("修改的id——" + this.form.id)await updateBaConserveBoq(this.form).then(async response => {this.msgSuccess("修改成功");this.open = false;await this.getList();//根据上级数据//如果上级是顶层,不校验if (this.form.parentId !== '0') {const storedData = this.dataMap.get(this.form.parentId);await this.load2(this.form.parentId, storedData.treeNode, storedData.resolve)}});} else {addBaConserveBoq(this.form).then(async response => {this.msgSuccess("新增成功");this.open = false;await this.getList();//console.log("我是本级ID===" + this.form.parentId) //上级id//新增不用 下面的if (this.form.parentId === '0' || this.form.parentId === null || this.form.parentId === 0) return//刷新外部数据(同级)//刷新本节点,直接把新数据的父类id 当作id,然后使用let newId;//应该用 newId 的 父类id,去数据库查询父类idawait selectParentIdById(this.form.parentId).then(async response => { //父类id就是我的id,用我的id去寻找 我的 父类id//console.log("返回的是:"+JSON.stringify(response))newId = response.data //这是我的父类id ,也就是上级的})//console.log("调用上级,刷新本级 的 id =="+newId)//上级id不可能等于0//如果 是第一层新增,不用刷新本层if (newId !== '0') {//根据上级id,刷新 上级 id (影响本级)const storedData3 = this.dataMap.get(newId);//刷新本级await this.load2(newId, storedData3.treeNode, storedData3.resolve)}//刷新内部的数据//判断是否已经展开const storedData4 = this.dataMap.get(this.form.parentId); // 判断自己是否展开if (storedData4 !== '' && storedData4 !== null && storedData4 !== undefined) { //如果没有数据,则证明自己没有展开//console.log("刷新内部数据====")//如果有数据,展开了,刷新下级数据await this.load2(this.form.parentId, storedData4.treeNode, storedData4.resolve)}// console.log(this.tableData1,'data1')});}}});},/** 删除按钮操作 */async handleDelete(row) {await this.$confirm('是否确认删除?', "警告", {confirmButtonText: "确定",cancelButtonText: "取消",type: "warning"}).then(async () => {await delBaConserveBoq(row.id);}).then(async () => {await this.getList();const storedData4 = this.dataMap.get(row.parentId);storedData4.tree.hasChildren = !!storedData4.treeNode.children.length// console.log(storedData4,'storedData4')// this.await this.load2(row.parentId, storedData4.treeNode, storedData4.resolve);await this.msgSuccess("删除成功");});},}
};
</script><style scoped>
.spec-dialog /deep/ .el-dialog {height: 55% !important;
}.deleted {display: none;
}
</style>