目錄
1.?源碼
2.?其他頁面引用
ps:請看完看明白再復用?
1.?源碼
<template><div style="width: 100%; height: 100%" class="form-condition"><!-- 普通表單 --><el-card shadow="hover" class="cardheight"><div class="form-content"><el-form ref="FormRef" label-width="auto" :model="FormRef"><el-rowv-for="(formType, indexs) in formTypeArray":key="indexs":gutter="20"><!-- <el-button @click="Text(formTypeArray[indexs])"></el-button> --><el-col:span="formTypeArray[indexs].length < 2 ? 24 : span"v-for="(data, index) in formTypeArray[indexs]":key="index"><!-- 關于Id相關的均不顯示,此處需要后臺進行配合完成 --><!-- &&(data.label? data.label.includes('ID')? false: true: false) --><el-form-itemv-if="data.type !== 'allCheckBox' &&data.type !== 'checkbox' &&(data.label? data.label.includes('ID')? false: true: false)":label="data.label":prop="data.prop":rules="rules(data)"><!-- :label="data.label.includes('ID') ? '序號' : data.label" --><!-- active-text="打開" --><!-- inactive-text="關閉" --><el-switchv-if="data.type == 'switch'"v-model="FormRef[data.prop]"class="mb-2"style="--el-switch-on-color: #13ce66;--el-switch-off-color: #ff4949;":active-value="1":inactive-value="0":disabled="data.disabled"@change="SwitchChang($event,formTypeArray[indexs][index],indexs,index)"/><!-- 輸入框類型 --><!-- 修改點 去除 v-model.number="FormRef[data.prop]" 202302002--><el-inputv-if="data.type == 'input'"v-model="FormRef[data.prop]":placeholder="data.placeholder":disabled="data.disabled"suffix-icon="xxxx"></el-input><!-- 時間類型 --><el-date-pickerpopper-class="date-style"v-if="data.type == 'date'"type="datetime":placeholder="data.placeholder"v-model="FormRef[data.prop]"format="YYYY/MM/DD HH:mm:ss"value-format="YYYY-MM-DD HH:mm:ss"style="width: 100%":disabled="data.disabled"></el-date-picker><!-- 下拉框類型 --><el-select:popper-append-to-body="false"v-if="data.type == 'select'":multiple="data.multiple":clearable="data.clearable"v-model="FormRef[data.prop]":placeholder="data.placeholder":change="SelectChange(FormRef[data.prop], data.label)"style="width: 100%":disabled="data.disabled"><el-optionv-for="(item, i) in data.option":key="item.value":label="item.label":value="item.value"></el-option></el-select><!-- lu 文本域--><!-- 輸入框類型 --><el-inputv-if="data.type == 'inputText'"type="textarea"v-model="FormRef[data.prop]":placeholder="data.placeholder":disabled="data.disabled"suffix-icon="xxxx"></el-input><el-checkboxv-if="data.type == 'Radio'":true-label="1":false-label="0"v-model="FormRef[data.prop]":label="'點擊激活此項為' + data.label + '產品售后信息'"border/><!-- 顯示帶有“check-on-click-node”的復選框:樹形下拉框 --><el-tree-selectv-if="data.type == 'treeSelect'"v-model="FormRef[data.prop]":data="data.option"check-strictly:render-after-expand="false"show-checkboxcheck-on-click-nodestyle="width: 100%":disabled="data.disabled":multiple="data.multiple"/><!-- 上傳控件 --><el-uploadv-if="data.type == 'upload'"action="#"multiple:auto-upload="true"accept="jpg,jpeg,png,PNG"list-type="picture-card":file-list="files":http-request="uploadFile":before-upload="beforeUpload":on-preview="handlePictureCardPreview":on-change="ChangeImage":on-remove="handleRemove"><el-icon><Plus /></el-icon></el-upload><!-- <el-button @click="SubPicForm">提交上傳</el-button> --><el-dialog v-model="dialogVisible"><img style="width: 100%" :src="dialogImageUrl" alt="" /></el-dialog></el-form-item><el-rowv-if="data.type == 'allCheckBox' &&JSON.stringify(data.childList) !== '{}'"class="allcheckBoxOther"><el-form-item label-width="auto" label="隨帶資料"><div v-for="(checkBoxData, key) in data.childList" :key="key"><el-form-item label-width="auto"><el-checkboxborder:true-label="1":false-label="0":label="checkBoxData.label"v-model="FormRef[checkBoxData.prop]"></el-checkbox></el-form-item></div></el-form-item></el-row></el-col></el-row><el-row style="width: 100%; height: 32px; padding-top: 10px"><el-col :span="span" style="width: 100%; margin: 0 auto"><el-form-item style="width: 100%"><div class="content-btn" style="margin: auto"><el-buttonplaintype="danger"style="float: left; margin-right: 15px"@click="cleanFormValue"><el-icon><FolderRemove /></el-icon>  清 空</el-button><el-buttonplaintype="primary"style="float: left"@click="getCondition()"><el-icon><Search /></el-icon> {{isOpenSonDataTable || isOpenSonTransfer ? "保存" : "提 交"}}</el-button></div></el-form-item></el-col></el-row></el-form></div></el-card><!-- 是否存在明細附表 --><div v-if="isOpenSonDataTable"><!-- 表單 --><el-card shadow="hover"><!-- 表單按鈕組件 --><div style="margin-bottom: 10px"><ButtonView ref="ButtonRef" @ButtonMessage="GetBtnClick"></ButtonView></div><!-- 數據表格組件 --><div class="aa"><TableDialogref="tableSonDataRef"@getPage="GetDataFenYeWath"@tableMessage="GetTableMessage"></TableDialog></div></el-card></div><!-- 抽屜,明細表編輯處 :before-close="drawerCloseSonForm"--><el-drawer:key="itemKey":title="dialogTitle"v-model="dialog"direction="ltr":size="drawerSize"custom-class="demo-drawer"ref="drawer"destroy-on-close><div class="demo-drawer__content"><!-- 表單組件 --><FromViewref="SonfromView"@conditionParams="GetCondition"@conditionFormData="GetConditionFormData"@SonSelectChange="GetSonSelectChange"></FromView></div></el-drawer><!-- 是否存在其他組件 --><div v-if="isOpenSonTransfer"><el-card shadow="hover" style="height: 439px"><p style="text-align: center; margin: 0 0 20px">請選擇左側的數據項,點擊中間“>”按鈕添加數據項</p><div style="text-align: center"><div><el-transferstyle="text-align: left; display: inline-block"v-model="transferValue":data="transferDatas":props="{label: 'title',}"filterable:titles="['待選數據', '已選數據']":button-texts="['取消', '選擇']"></el-transfer></div><el-button plain class="squan" type="success" @click="Authorization()">綁 定</el-button></div></el-card></div></div>
</template><script>
import { computed, provide, inject, ref } from "@vue/runtime-core";
import { watchEffect, getCurrentInstance, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";export default {name: "FromView",emits: ["conditionParams"],setup(props, context) {let FormRefTest = reactive({});let span = ref(6); //6let formTypeArray = ref(new Array());//用于接收父組件傳遞的Form表單配置const formTypeConfig = inject("formTypeConfig");//行數let formRowsCount = inject("formRowsCount");let checkBoxList = [{type: "allCheckBox",label: "allCheckBox",childList: {},},];//移位,將特定的元素移到最后function moveArray(arr, sourceIndex, targetIndex) {// splice 將目標元素替換并將原結果扔回來賦值給它arr[sourceIndex] = arr.splice(targetIndex, 1, arr[sourceIndex])[0];}/*** 設置表單類型* @param array 表單配置* @param col 每行表單項個數*/const setFormType = (oldArray, col) => {formTypeArray = ref(new Array());//console.log("進入FormView組件中的方法", formTypeArray);//console.log(oldArray, col);let array = [];oldArray.map((item) => {if (item.type == "checkbox") {checkBoxList[0].childList[item.prop] = item;array.push(item);} else {array.push(item);}});//console.log("checkBoxList====", checkBoxList);//console.log("array====", array);//#region 移動 checkbox 參數位置//移動var sourceIndexes = [];array.forEach((item, index) => {if (item.type && item.type == "checkbox") {sourceIndexes.push(index);}});// 遍歷索引數組,移動元素sourceIndexes.forEach((sourceIndex) => {moveArray(array, sourceIndex, array.length);});//過濾undefinedarray = array.filter((item) => {return item !== undefined || !!item;});//#endregionif (col == null || col == "" || array == null || array == "") {col = 4; // 默認分4列}span.value = 24 / col;if (array != null) {array.map((item) => {FormRefTest[item.prop] = item.value;});//console.log("==========FormRef=====", FormRefTest);// 只有一行if (col >= array.length) {formTypeArray.value.push(array);} else {// 超過一行let deb = col;let i = 0;while (i < array.length) {let item = []; //nullvar isFlag = false; //當它為True時,下方將不再Pushwhile (i < deb) {if (array[i].label.indexOf("后臺自增ID") !== -1) {item.push(array[i]);i++;break;} else if (array[i].label.indexOf("備注") !== -1 ||array[i].label.indexOf("概述") !== -1 ||array[i].label.indexOf("附件") !== -1 ||array[i].type.indexOf("inputText") !== -1) {//說明在此之前已有數據if (item.length > 0) {isFlag = true;formTypeArray.value.push(item);item = [];}item.push(array[i]);i++;break;} else {item.push(array[i]);//console.log(deb);i++;}}if (!isFlag) {formTypeArray.value.push(item);}if (array.length - i < col) {deb = array.length;} else {deb = i + col;}}formTypeArray.value.push(checkBoxList);}}//console.log("---------表單配置數據 SUCCESS----------");};//#region 明細表配置//用于監聽子表表單數據let FatherisOk = ref(false);//用于父表單保存后的Idlet FatherIds = ref(0);//用于監聽子表單中的數據let SonConfigCondition = ref([]);//用于監聽子表一行幾個let SonformRowsCount = ref(1);//明細表單配置const ConfigurationCondition = () => {provide("formTypeConfig", SonConfigCondition);provide("formRowsCount", SonformRowsCount);};//#endregion//#region 穿梭框配置//#endregion// 監聽表單配置數據 數據變化時, 更新配置watchEffect(() => {//console.log("-------監聽formTypeConfig--------");//console.log("=formTypeConfig==========", formTypeConfig);//console.log(formRowsCount);var rowlCount = formRowsCount == undefined ? 1 : formRowsCount.value;setFormType(formTypeConfig.value, rowlCount);});return {formTypeArray,span,//cleanFormValue,setFormType,ConfigurationCondition, //明細表單配置SonConfigCondition,FatherisOk, //用于子表判斷附表是否已經保存FatherIds, //若主表已經保存,此字段不為0且同時可以獲取主表新增數據后的IdformRowsCount, //行數//#region 穿梭框配置FormRefTest,//#endregion};},data() {return {FormRef: {},checkBoxList: {},isOpenSonDataTable: false, //是否存在明細表格isOpenSonTransfer: false, //是否存在其他組件listData: [], //此處我子表單中選擇的數據,用于對其修改、刪除使用GetDataFenYe: null, //分頁查詢數據GetDataHanderAndFrom: null, //明細表表頭查詢數據dialog: false,dialogTitle: "",itemKey: "",transferValue: [], //穿梭框選中的transferDatas: [], //穿梭框數據源//上傳如下:files: [],dialogVisible: false,dialogImageUrl: "",deleteFiles: [],//抽屜大小drawerSize: "22%",};},created() {//默認初始化明細表單配置this.ConfigurationCondition();this.FormRef = this.FormRefTest;//console.log("this.FormRef====", this.FormRef);//console.log("this.FormRefTest====", this.FormRefTest);},methods: {Text(val) {},rules(data) {//#region 自定義驗證校驗if (data.isRules) {//校驗數值類型if (data.propTypes == "INT") {var validatorTel = (rule, value, callback) => {if (!value) {return callback(new Error(data.label + "不能為空"));}var numReg = /^[0-9]+$/;var numRe = new RegExp(numReg);if (!numRe.test(value)) {callback(new Error("請輸入數字值"));} else {callback();}};return [{required: true,validator: validatorTel,trigger: "blur",},];}}//#endregion//校驗手機號 regMobile//暫時屏蔽校驗手機號,此處不完善,目前只打開校驗是否為空//20230202留// const regMobile =// /^((\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14})|([1][3,4,5,6,7,8,9][0-9]{9})$/;// if (data.prop.includes("Tel")) {// var validatorTel = (rule, value, callback) => {// if (!value) {// return callback(new Error(data.label + "不能為空"));// }// var numReg = /^[0-9]+$/;// var numRe = new RegExp(numReg);// if (!numRe.test(value)) {// callback(new Error("請輸入數字值"));// } else {// if (!regMobile.test(value)) {// callback(new Error("請輸入正確的號碼"));// } else {// callback();// }// }// };// return [// {// required: true,// validator: validatorTel,// trigger: "blur",// },// ];// } elseif (data.prop == "LoginAccount" ||data.prop == "Password" ||data.prop.includes("Eqipment") ||data.prop == "ProductID" ||data.prop == "PartID" ||data.prop == "WorkNo" ||data.prop == "QualityCode") {if (data.type === "select") {return [{ required: true, message: "此處為必填項", trigger: "change" },];}if (data.type === "input") {return [{ required: true, message: "此處為必填項", trigger: "blur" }];}}},SwitchChang(data, formData, indexs, index) {// this.FormRef[data.prop] = data ? 1 : 0;//},//實時監聽子組件發送的信息GetDataFenYeWath(Msg) {//重新賦值,避免新增、修改、刪除操作this.pageSize = Msg.pageSize;this.pageNum = Msg.pageNum;let param = {params: Msg,};if (this.GetDataFenYe != null) {this.GetDataFenYe(param);}this.$emit("SongetPage", { pageSize: this.pageSize, pageNum: this.pageNum });},//獲取表格組件傳遞的信息GetTableMessage(msg) {//獲取listDatas值this.listData =msg.type === "列表選擇"? msg.listData: msg.type === "頁碼切換"? null: null;//console.log("組件:表格發送信息:" + this.listData);},//選擇框事件SelectChange(data, labels) {console.log(labels);var linsDatas = { value: data, label: labels };//匹配新格式var datas = {data: linsDatas,type: "選擇",};//選擇框事件,回傳給父組件this.$emit("SonSelectChange", datas);},/*** 獲取父組件傳遞過來的數據信息鏈,這里指isOpenSonTransfer 穿梭框的數據*/SetDataSonTransfer(SonDataTransFer) {this.isOpenSonTransfer = SonDataTransFer.isOpenSonTransfer; //是否開啟穿梭框var tData = SonDataTransFer.SonTransfer; //穿梭框左側數據//為True的情況下,進行渲染明細if (this.isOpenSonTransfer) {//每次選擇后清空,重新觸發this.transferDatas = [];this.transferDatas = tData;}},/*** 獲取父組件傳遞過來的數據信息鏈,這里指isOpenSonTransfer 穿梭框的數據*/SetDataSonTransferDatas(SonDataTransFer) {this.isOpenSonTransfer = SonDataTransFer.isOpenSonTransfer; //是否開啟穿梭框var SonTransferValue = SonDataTransFer.SonTransferValue; //穿梭框右側數據//為True的情況下,進行渲染明細if (this.isOpenSonTransfer) {//每次選擇后清空,重新觸發this.transferValue = [];var ChangeLst = [];SonTransferValue.forEach((element) => {ChangeLst.push(element.PartID.toString());});this.transferValue = ChangeLst;}},//綁定按鈕Authorization() {// 優先判斷在新增的情況下,主表是否已經完成了保存 多用于子表進行新增操作if (!this.FatherisOk) {//警告this.$message({message:"在新建明細信息的情況下,請優先添加主表信息,再對其明細表進行新增編輯操作",type: "warning",});return;}this.formTypeArray;this.transferValue;var datas = {form: this.formTypeArray,transDatas: this.transferDatas,trans: this.transferValue,FatherIds: this.FatherIds,type: "綁定",};this.$emit("SonSelectChange", datas);},/*** 獲取父組件傳遞過來的數據信息鏈,不包含明細表數據* @param {} GetDataLists*/SetData(SonDataTableDatas) {this.isOpenSonDataTable = SonDataTableDatas.isOpenSonDataTable;//為True的情況下,進行渲染明細if (this.isOpenSonDataTable) {//渲染 —— 延遲加載this.$nextTick(() => {this.$nextTick(() => {//自動高度this.$refs.tableSonDataRef.heights = "auto";});//普通表格this.$refs.tableSonDataRef.SetTableType(true);//組件渲染表頭表單this.$refs.tableSonDataRef.SetDataTableHeader(SonDataTableDatas.GetDataHanderAndFrom);//添加子表表單數據this.SonConfigCondition =SonDataTableDatas.GetDataHanderAndFrom.lstSubset[0].Froms;//渲染明細按鈕this.$refs.ButtonRef.SetButtonConfigDatas(SonDataTableDatas.PartButtonList);});}},//接收父組件傳遞的明細表數據,通過此方法作為媒介進行對孫組件傳值SetDataSonTable(GetDataFenYe) {this.$nextTick(() => {//若編輯一條裝備主表數據時,存在部件表,此處需要賦值this.$refs.tableSonDataRef.SetDataTable(GetDataFenYe);// this.dialog = false;});},//獲取按鈕組件消息————————用于明細表單GetBtnClick(val) {//拿到組件信息后,新增、修改彈出Dalodif (val.search("新增") != -1) {// 優先判斷在新增的情況下,主表是否已經完成了保存 多用于子表進行新增操作if (!this.FatherisOk) {//警告this.$message({message:"在新建明細信息的情況下,請優先添加主表信息,再對其明細表進行新增編輯操作",type: "warning",});return;}// 優先添加this.dialog = true;this.dialogTitle = val;// //優先清空// this.$refs.SonfromView.CloseSonForm();var parm = { type: "新增" };this.$emit("GrandsonFormArr", parm);}if (val.search("編輯") != -1) {//僅支持單條編輯if (JSON.parse(JSON.stringify(this.listData)).length != 1) {//警告this.$message({message: "請選擇一條數據進行編輯操作!",type: "warning",});return;}//結構剖析var newListData = JSON.parse(JSON.stringify(this.listData));//循環表單this.SonConfigCondition.forEach((item) => {newListData.forEach((dataitem) => {//循環找Keyfor (let key in dataitem) {if (item.prop == key) {item.value = dataitem[key];}}});});//先打開this.dialog = true;this.dialogTitle = val;if (newListData[0].Files !== undefined &&newListData[0].Files !== null) {//剔除特殊字符var newFilesString = newListData[0].Files.replace(/"/g, "");//分割數組var newFilesArr = newFilesString.replace(/"/g, "").split("|");//刪除最后一位,總是多出的空 ''newFilesArr.pop();//此處延遲加載會幫你解決一切this.$nextTick(() => {var newFiles = [];//構建回顯所需要的參數值newFilesArr.forEach((element) => {var file = { url: this.$FWurl + element };newFiles.push(file);});//組件渲染this.$refs.SonfromView.SetFilesData(newFiles);});}var parm = { type: "編輯", Ids: newListData[0].ID };this.$emit("GrandsonFormArr", parm);}if (val.search("刪除") != -1) {this.$nextTick(() => {var _this = this;//僅支持單條編輯if (JSON.parse(JSON.stringify(this.listData)).length != 1) {//警告this.$message({message: "請選擇一條數據進行刪除操作!",type: "warning",});return;}//結構剖析var newListData = JSON.parse(JSON.stringify(this.listData));//此參數在刪除時無需傳遞delete newListData[0].id;ElMessageBox.confirm("確認刪除這條信息嗎?", "警告", {confirmButtonText: "確定",cancelButtonText: "取消",type: "warning",}).then(() => {let dataParam = { data: newListData[0], type: "刪除" };this.$emit("SonFormArr", dataParam);}).catch(() => {});});}},//給孫組件的抽屜添加寬度SetDrawerSize(value) {//渲染 —— 延遲加載this.$nextTick(() => {//重新渲染,itemKey用于處理Table不渲染的問題this.drawerSize = value;});},//孫組件獲取父組件傳遞的File信息GetConditionFormData(datas) {// Ids雖然是從父級得來,但是此處可能會丟失Ids,所以需要將孫級位面中Ids獲取,也就是明細Id//先刪后加,垃圾FormData特性datas.delete("Ids");datas.append("Ids", this.FatherIds); //屬于哪條明細表數據this.$emit("conditionFormData", datas);},//獲取表單組件傳遞的信息,此處接收的表單乃是數據表格對應的表單————————用于明細表單GetCondition(datas) {//console.log("組件:表單組件發送信息:" + datas);var formDatas = {};formDatas = datas;// datas.forEach((e, index) => {// for (let i = 0; i < e.length; i++) {// var keys = datas[index][i].prop;// var values = datas[index][i].value;// formDatas[keys] = values;// }// });const param = formDatas;//獲取表單組件后,判斷是新增/修改if (this.dialogTitle.search("新增") != -1) {//將新增后的主表Id拿到后進行新增操作,此處需要回傳到最外層的組件中param.FatherIds = this.FatherIds;let dataParam = { data: param, type: "新增" };this.$emit("SonFormArr", dataParam);}if (this.dialogTitle.search("編輯") != -1) {param.FatherIds = this.FatherIds;let dataParam = { data: param, type: "編輯" };this.$emit("SonFormArr", dataParam);}},//清空子表表單數據CloseSonForm() {//清空選擇this.cleanFormValue();},//抽屜回調,關閉前清空表單數據drawerCloseSonForm(done) {//清空選擇this.$refs.SonfromView.CloseSonForm();done();},/*** 清空表單內容*/cleanFormValue() {for (let key in this.FormRef) {this.FormRef[key] = "";}},//#region 關于圖片組上傳uploadFile(file) {//console.log(file);},//刪除事件handleRemove(file, fileList) {var obj = file.url.split("upLoad/").slice(-1)[0];//添加 需要刪除的附件this.deleteFiles.push(obj);//console.log(file, fileList);},//預覽事件handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogVisible = true;},//添加圖片ChangeImage(file, filelist) {this.files = filelist;//console.log("-----------" + JSON.stringify(file));},/*** 給父組件返回表單輸入的內容*//// lugetCondition() {this.$refs.FormRef.validate((valid) => {//console.log("valid===", valid);if (valid) {var formData = new FormData();this.files.forEach((item) => {if (!(!item.raw && item.url.indexOf("blob") === -1)) {formData.append("file", item.raw);}});formData.append("Ids", this.FatherIds); //屬于哪條主表數據this.deleteFiles.forEach((item) => {formData.append("fileByDelete", item); //刪除的集合});// //console.log(333333, this.formTypeArray);this.$emit("conditionParams", this.FormRef);this.$emit("conditionFormData", formData);} else {// this.$message("請輸入內容");return false;}});},/*** 回顯*/SetFilesData(FilesList) {//渲染 —— 延遲加載this.$nextTick(() => {this.files = [];this.files = FilesList;});},//#endregion//子組件中選擇框事件GetSonSelectChange(datas) {if (datas.type == "選擇") {this.$emit("GrandsonSelectChange", datas);}if (datas.type == "綁定") {this.$emit("GrandsonSelectChange", datas);}},},
};
</script>
<style lang="scss" scoped>
.allcheckBoxOther div:not(:first-child) {margin-left: 1% !important;:deep(.el-form-item__label-wrap) {margin-bottom: 20% !important;margin-left: 1% !important;}
}
.aa ::v-deep .el-scrollbar {height: 100px;
}
//卡片與“新增”字樣之間的距離,卡片的padding-top 為0
.el-dialog--center .el-dialog__body {text-align: initial;padding: 0px calc(var(--el-dialog-padding-primary) + 5px) 30px !important;
}
</style>
2.?其他頁面引用
<template><el-row :gutter="20"><el-col :span="4"><div><!-- 樹形列表組件 --><el-collapse v-model="activeNames" @change="handleChange"><el-collapse-item style="text-align: center" title="字典項" name="1"><TreeViewref="TreeRef"@TreeViewMessage="GetTreeMessage":defaultSelected="defaultSelected"nodeKey="DictID"></TreeView></el-collapse-item></el-collapse></div></el-col><el-divider direction="vertical">分割線</el-divider><el-col :span="19"><div><!-- 表單按鈕組件 --><div style="margin-bottom: 10px"><ButtonView @ButtonMessage="GetBtnClick"></ButtonView></div><!-- 數據表格組件 --><div style="width: 103%"><TableDialogref="tableRef"@getPage="GetDataFenYeWath"@tableMessage="GetTableMessage"@treeMessage="GetTreeMessage1"></TableDialog></div></div></el-col></el-row><!-- 彈出框,用于新增、修改 --><el-dialogv-model="dialogVisible":title="dialogTitle"width="30%"centerdraggabledestroy-on-close><!-- 表單組件 --><FromViewstyle="margin-top: -25px"ref="fromViewRef"@conditionParams="GetCondition"></FromView></el-dialog><!-- <el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop> -->
</template><script>
import { provide, reactive, ref } from "@vue/runtime-core";
import { ElMessage, ElMessageBox } from "element-plus";export default {name: "Sys_DictTable",data() {return {activeNames: ["1"], //左側的折疊用戶,默認展開dialogVisible: false, //用于控制新增、編輯dialogTitle: "", //用于控制新增、編輯標題listData: [], //已選擇的數據Dictid: "",defaultSelected: "",selectedDictIDs: "", //左側樹勾選的id(多選)};},setup() {//默認頁大小let pageSize = 20;let pageNum = 1;let total = 0;//用于監聽選中的數據列表let ConfigCondition = ref([]);//表單配置const ConfigurationCondition = () => {provide("formTypeConfig", ConfigCondition);};//表格配置const ConfigurationTable = () => {var tableHeader = []; // 設置表頭 [fieldName字段名, label列名, width列寬, sortable排序]var tableDatas = []; // 表格數據// 設置表頭 [fieldName字段名, label列名, width列寬, sortable排序]// 配置表頭數據provide("tableHeaderConfig", tableHeader);// 配置單元格數據及屬性/ 分頁配置默認值provide("tableDataConfig", {tableData: tableDatas,});};//樹形列表配置const ConfigurationTree = () => {provide("TreeConfig", { isTreeSeleteOrBtn: 1 });};//按鈕配置const ConfigurationButton = () => {let CfgButtonDatas = [];CfgButtonDatas = [{btnName: "新增",btnType: "success",plain: true, //簡約按鈕類型,與UI相關SvgIconName: "Insert",},{btnName: "編輯",btnType: "primary",plain: true,SvgIconName: "Update",},{btnName: "刪除",btnType: "danger",plain: true,SvgIconName: "Delete",},];provide("ButtonTypes", { type: 1 }); // 通常使用默認 1 按鈕provide("ButtonConfig", { CfgButtonDatas: CfgButtonDatas });};//注冊高級篩選查詢配置、表單配置return {pageSize,pageNum,total,ConfigCondition, //表單數據,實時傳遞回ConfigurationCondition,ConfigurationTable,ConfigurationTree,ConfigurationButton,};},created() {//初始化配置this.ConfigurationCondition();this.ConfigurationTable();this.ConfigurationTree();this.ConfigurationButton();//加載表單、表格列頭this.GetColDataList();// Get請求下,必須要在對象內添加params 參數,再嵌套一層,否則無法識別const param = {params: {pageSize: this.pageSize,pageNum: this.pageNum,},};// this.GetDataFenYe(param);//獲取部門樹形列表this.GetDepartMentGetDataTree();},mounted() {},methods: {//實時監聽子組件發送的信息GetDataFenYeWath(Msg) {//重新賦值,避免新增、修改、刪除操作this.pageSize = Msg.pageSize;this.pageNum = Msg.pageNum;let param = {params: Msg,};this.GetDataFenYe(param);},//獲取用戶數據,用戶數據綁定在某個模塊節點下,默認查詢所有GetDepartMentGetDataTree() {//Get請求下,必須要在對象內添加params 參數,再嵌套一層,否則無法識別const param = {params: {},};this.$API.DicGetDataTree(param).then((res) => {//組件渲染// console.log("樹", res.data.Data.lstSubset[0].DictID);this.defaultSelected = [res.data.Data.lstSubset[0].DictID];this.selectedDictIDs = [res.data.Data.lstSubset[0]];this.$refs.TreeRef.SetTreeDatas(res.data.Data.lstSubset);const param = {params: {pageSize: this.pageSize,pageNum: this.pageNum,DictIDs: res.data.Data.lstSubset[0].DictID,},};this.GetDataFenYe(param);}).catch((err) => {// this.$notify.error({// title: "消息提示",// message: err,// });});},//獲取用戶數據,用戶數據綁定在某個模塊節點下,默認查詢所有GetColDataList() {//Get請求下,必須要在對象內添加params 參數,再嵌套一層,否則無法識別const param = {params: { param: "1" },};this.$API.DicGetColDataList(param).then((res) => {//組件渲染this.$refs.tableRef.SetDataTableHeader(res.data.Data);//直接將此數據類型貫通至組件中this.ConfigCondition = res.data.Data.lstSubset[0].Froms;}).catch((err) => {// this.$notify.error({// title: "消息提示",// message: err,// });});},//查詢分頁數據GetDataFenYe(param) {this.$API.DicGetDataFenYe(param).then((res) => {//組件渲染console.log("數據", res.data.Data);this.$refs.tableRef.SetDataTable(res.data.Data);}).catch((err) => {// this.$notify.error({// title: "消息提示",// message: err,// });});},/*** 新增* @param {*} data*/InsertFormDatas(data) {this.$API.DicInsertData(data).then((res) => {ElMessage({type: "success",message: res.data.Msg,});this.CloseForm();this.dialogVisible = false;const param = {params: {pageSize: this.pageSize,pageNum: this.pageNum,DictIDs: data.DictID,},};this.GetDataFenYe(param);}).catch((err) => {this.$notify.error({title: "消息提示",message: err,});});},/*** 修改* @param {} data*/UpdateFormDatas(data) {this.$API.DicUpdateData(data).then((res) => {ElMessage({type: "success",message: res.data.Msg,});this.CloseForm();this.dialogVisible = false;const param = {params: {pageSize: this.pageSize,pageNum: this.pageNum,DictIDs: data.DictID,},};this.GetDataFenYe(param);}).catch((err) => {this.$notify.error({title: "消息提示",message: err,});});},/*** 刪除* @param {*} data*/DeleteFormDatas(data) {this.$API.DicDeletData(data).then((res) => {ElMessage({type: "success",message: res.data.Msg,});this.CloseForm();this.dialogVisible = false;const param = {params: {pageSize: this.pageSize,pageNum: this.pageNum,DictIDs: data.DictID,},};this.GetDataFenYe(param);}).catch((err) => {this.$notify.error({title: "消息提示",message: err,});});},//獲取表單組件傳遞的信息,此處接收的表單乃是數據表格對應的表單GetCondition(datas) {console.log("組件:表單組件發送信息:" + datas);var formDatas = {};// datas.forEach((e, index) => {// for (let i = 0; i < e.length; i++) {// var keys = datas[index][i].prop;// var values = datas[index][i].value;// formDatas[keys] = values;// }// });const param = datas;//獲取表單組件后,判斷是新增/修改if (this.dialogTitle.search("新增") != -1) {this.InsertFormDatas(param);}if (this.dialogTitle.search("編輯") != -1) {console.log("param===========", param);this.UpdateFormDatas(param);}},//獲取表格組件傳遞的信息GetTableMessage(msg) {//獲取listDatas值this.listData =msg.type === "列表選擇"? msg.listData: msg.type === "頁碼切換"? null: null;console.log("組件:表格發送信息:" + this.listData);},//獲取樹形組件傳遞的信息GetTreeMessage(val) {console.log("valaaa", val.data);let NodeList = JSON.parse(JSON.stringify(val.data));this.selectedDictIDs = val.data;let newParam = "";NodeList.forEach((element) => {newParam = newParam + element.DictID + ",";});//去掉最后一個逗號(如果不需要去掉,就不用寫)if (newParam.length > 0) {newParam = newParam.substr(0, newParam.length - 1);}console.log("--------組件:樹形列表解析后:" + newParam);const param = {params: {pageSize: this.pageSize,pageNum: this.pageNum,DictIDs: newParam,},};this.GetDataFenYe(param);},//折疊面板用戶handleChange(val) {},//獲取按鈕組件消息GetBtnClick(val) {//拿到組件信息后,新增、修改彈出Dalodif (val.search("新增") != -1) {// this.CloseForm();this.$nextTick(() => {this.$refs.tableRef.ClearSelect();});//luif (JSON.parse(JSON.stringify(this.selectedDictIDs)).length != 1) {//警告this.$message({message: "請選擇一條字典項進行新增操作!",type: "warning",});return;}//循環表單var newSelectData = JSON.parse(JSON.stringify(this.selectedDictIDs));this.ConfigCondition.forEach((item) => {newSelectData.forEach((dataitem) => {//循環找Keyfor (let key in dataitem) {if (item.prop == key && key == "DictID") {item.value = dataitem[key];}}// item[0].value = defaultSelected;});});console.log("ConfigCondition===", this.ConfigCondition);this.dialogVisible = true;this.dialogTitle = val + "字典項";}if (val.search("編輯") != -1) {//僅支持單條編輯if (JSON.parse(JSON.stringify(this.listData)).length != 1) {//警告this.$message({message: "請選擇一條數據進行編輯操作!",type: "warning",});return;}//結構剖析var newListData = JSON.parse(JSON.stringify(this.listData));//循環表單this.ConfigCondition.forEach((item) => {newListData.forEach((dataitem) => {//循環找Keyfor (let key in dataitem) {if (item.prop == key) {item.value = dataitem[key];}}});});this.dialogVisible = true;this.dialogTitle = val + "字典項";}if (val.search("刪除") != -1) {this.$nextTick(() => {var _this = this;//僅支持單條編輯if (JSON.parse(JSON.stringify(this.listData)).length != 1) {//警告this.$message({message: "請選擇一條數據進行刪除操作!",type: "warning",});return;}//結構剖析var newListData = JSON.parse(JSON.stringify(this.listData));ElMessageBox.confirm("確認刪除這條信息嗎?", "警告", {confirmButtonText: "確定",cancelButtonText: "取消",type: "warning",}).then(() => {_this.DeleteFormDatas(newListData[0]);}).catch(() => {});});}},//清空表單數據,解決選中某行時,點擊新增按鈕,響應ConfigCondition參數的清空以及取消選擇CloseForm() {this.$nextTick(() => {//循環表單清空this.ConfigCondition.forEach((item) => {item.value = "";});//清空選擇this.$refs.tableRef.ClearSelect();});},},
};
</script><style lang="scss" scoped>
.el-divider--vertical {display: inline-block;width: 1px;height: 53em;margin: 0 8px;vertical-align: middle;position: relative;border-left: 1px var(--el-border-color) var(--el-border-style);
}
</style>