日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

select 框添加樹結構(todu)

作者:樂~~~ 更新時間: 2023-07-28 編程語言

目錄

1.?案例:

?2.?代碼

2.1 html部分

2.2 script部分

3.?父子頁面完整代碼(可不看)

?3.1?父組件

3.2?子組件


1.?案例:

?2.?代碼

2.1 html部分
 <el-form
      ref="newFrom"
      :form="form"
      :model="newFrom"
      :rules="rules"
      label-width="100px"
      style="padding-left: 7px"
    >
<!-- ParentID: 父級的ID    ParentName:父節點名稱    -->
      <el-form-item
        label="父級名稱"
        prop="ParentID"
      >
        <el-select
          v-model="newFrom.ParentID"
          clearable
        >
          <!-- :label="item.Text" :value="item.ID"  input框顯示的值-->
          <el-option
            :key="newFrom.ParentID"
            :value="newFrom.ParentID"
            :label="newFrom.ParentName"
            placeholder="請選擇父節點"
            class="aa"
          >

 <!-- partendData:樹結構數據    handleNodeClick:樹結構點擊事件-->

            <el-tree
              :data="partendData"
              node-key="ID"
              :props="defaultProps"
              @node-click="handleNodeClick"
            ></el-tree>
          </el-option>
        </el-select>
      </el-form-item>
      
    </el-form>
2.2 script部分
props: ["form", "formID", "partend"],  //父子傳值,這是接收父節點傳過來的值

//定義
data() {
    
    return {
      newFrom: {
        DataName: "", //名稱
        ParentID: "", //父節點ID
        SortID: "", //排序
        Dsc: "", //備注
        DictID: "", //與左側關聯ID
        DataID: "", //字典編號
        ParentName: "", //父節點名稱
      },
    
      //#region 父節點
      
      partendData: [], //1. 接收父組件傳遞過來的父節點的值
      defaultProps: {  //2. 下拉框的值
        children: "Children",
        label: "Text",
        id: "ID",
      },
      //#endregion
    };
  },

//監聽
watch: {
//監聽partend的變化(partend 這個值就是下拉框數據,我這邊是父組件查詢號,然后傳過來的)
    partend: {
      deep: true, //深度監聽
      immediate: true, //初始化時監聽
      handler(n, o) {
        this.partendData = n;  //把最新的值賦給partendData (定義的樹結構字典)
        console.log("監聽父節點數據的變化", n); 
      },
    },
  },

//方法
methods:{
  //點擊方法(下拉框點擊之后,吧選中的值賦給ParentID ,ParentName )
    handleNodeClick(val) {
      console.log(val, "zzzz");
      this.newFrom.ParentID = val.ID;
      this.newFrom.ParentName = val.Text;
      this.treeID = val.ID;
    },
}
3.?父子頁面完整代碼(可不看)
?3.1?父組件
<template>
  <div
    class="dictionaryIndex"
    style="width: 100%; height: 96%"
  >
    <div class="mainStyle">
      <el-row
        :gutter="6"
        style="width: 100%; height: 100%"
      >
        <el-col
          :span="3"
          style="padding-top: 3%;"
        >
          <div
            class="grid-content bg-purple"
            style="background-color: #fff"
          >
            <p class="jbTypeStyle">字典類型</p>
            <!-- defaultProps :這個里面的字段要與后端返回過來的字段一致 -->
            <!-- <el-tree>
              vue2 簡單插槽寫法
              <span
                class="custom-tree-node"
                slot-scope="{ node }"
              >
                <span> <i class="custom_icon"></i>{{ node.Text }} </span>
              </span>
            </el-tree> -->
            <el-tree
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
              node-key="ID"
              default-expand-all
              highlight-current
              :key="itemKey"
            >
              <!-- vue3 插槽寫法 -->
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>
                    <i class="custom_icon"></i>
                    {{ node.label }}
                  </span>
                </span></template>
            </el-tree>

          </div>
          <el-divider direction="vertical"></el-divider>
        </el-col>
        <el-col :span="21">
          <div class="dic_btnStyle">

            <ButtonView
              ref="ButtonRef"
              @ButtonMessage="GetBtnClick"
            />
          </div>
          <div>
            <cummonTable
              ref="cummonTable"
              :columns="columns"
              :pagination="pagination"
              @rowClick="GetrowClick"
            />
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="33%"
      center
      draggable
      destroy-on-close
      append-to-body
      class="dialogStyle"
      :before-close="handleClose"
    >
      <dictionaryForm
        ref="fromViewRef"
        :form="formData"
        :formID="formID"
        :partend="partend"
        @formClose="GetcloseData"
        @fathernewFrom="GetCondition"
      />
    </el-dialog>
  </div>
</template>

<script>
import dictionaryForm from "./dictionaryForm.vue";

// import { Message, Notification } from "element-ui";
// import { fakeApi } from "@/api/luApi.js";
// import { PublicFunction } from "@/utils/vuePublic";
import cummonTable from "@/components/zaojia/tableCommon/cummonTable.vue";
// import conButton from "@/layout/components/conButton.vue";

export default {
  inject: ["reload"],

  components: {
    dictionaryForm,
    cummonTable,
  },
  data() {
    return {
      dialogVisible: false, //用于控制form表單顯隱
      dialogTitle: "", //用于控制新增、編輯標題
      formData: {}, //定義對象,用于給子組件傳值
      // selectDictIDName: "", //用于給子組件傳 類型 值
      treeData: [], //定義左側樹初始化
      itemKey: "", //ces
      selectedDictIDs: "", //左邊樹勾選的ID
      selectLabel: "工程項目", //左側字典項名稱,默認是第一個
      defaultProps: {
        children: "Children", //要與后端返回過來的字段一致
        label: "Text", //要與后端返回過來的字段一致
      },
      //#region 傳給子table
      columns: {
        isSelect: false,
        showFenYe: false,
        isSelection: false,
        isTag: false,
        defaultall: true, //默認展開
        highlightCurrent: true, //高亮選中
      },
      pagination: {
        total: null,
      },
      multipleSelection: {}, //表格勾選的值
      tableData: [],
      //#endregion

      loading: false, //加載
      formID: 0, //默認是0,說明是新增

      //#region 父節點相關
      partend: null, //傳給子組件父節點的值
      //#endregion
      btnData: null, //調按鈕接口傳的參數
    };
  },
  created() {
    const param = {
      MenuID:
        localStorage.getItem("MenuIds") == "undefined"
          ? 0
          : localStorage.getItem("MenuIds"),
      RoleID:
        localStorage.getItem("RoleID") == "undefined"
          ? 0
          : localStorage.getItem("RoleID"),
    };
    //lu 用于查詢該菜單所擁有的按鈕
    this.$GetButtonByRoleAndMenus(param, this);
    this.btnData = param;
  },
  mounted() {
    this.SetTreeDatas(); //初始化左側數據
    this.GetColDataList(); //初始化表頭
  },
  methods: {
    //獲取點擊左側樹的數據
    handleNodeClick(data) {
      this.selectedDictIDs = data.Value; //ID 左側樹的唯一值
      this.selectLabel = data.Text;
      console.log("點擊樹的時候===", data);
      let param = { DictID: this.selectedDictIDs };
      this.getTabledata(param); //初始化表格數據
    },
    // 初始化按鈕
    GetBtnClick(value) {
      let _this = this;
      if (value == "新增") {
        if (this.selectedDictIDs == "") {
          this.$message({
            showClose: true,
            message: "請選擇字典類型",
            type: "warning",
          });
        } else {
          this.partend = this.tableData;
          console.log(
            this.multipleSelection,
            "選中的數據11111111111111",
            this.partend
          );
          if (this.multipleSelection != undefined) {
            this.dialogTitle = value;
            this.formData = {
              DataName: "", //名稱
              ParentID: this.multipleSelection.ID, //父節點ID
              SortID: "", //排序
              Dsc: "", //備注
              ID: 0,
              DataID: "", //字典編號
              DictID: this.selectedDictIDs, //與左側關聯ID
              ParentName: this.multipleSelection.Text,
            };
            this.dialogVisible = true;
          } else {
            this.dialogTitle = value;
            this.formData = {
              DataName: "", //名稱
              ParentID: 0, //父節點ID
              SortID: "", //排序
              Dsc: "", //備注
              ID: 0,
              DataID: "",
              DictID: this.selectedDictIDs, //與左側關聯ID
            };
            this.dialogVisible = true;
          }
        }
      } else if (value == "編輯") {
        this.dialogTitle = value;
        this.formData = this.multipleSelection;
        this.dialogVisible = true;
      } else if (value == "刪除") {
        this.$confirm("此操作將永久刪除該數據, 是否繼續?", "提示", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //調用方法
            this.DeleteFormDatas(this.multipleSelection);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消刪除",
            });
          });
      } else if (value == "新增子級") {
        this.dialogTitle = value;
        this.formData = {
          DataName: "", //名稱
          ParentID: this.multipleSelection.ID, //父節點ID
          SortID: "", //排序
          Dsc: "", //備注
          DictID: this.selectedDictIDs, //與左側關聯ID
        };
        this.dialogVisible = true;
      }
    },
    // 選中行數據
    GetrowClick(row) {
      // console.log("行選中數據", val);
      if (row != undefined) {
        if (this.multipleSelection == row) {
          console.log("再次點擊同一行,取消當前行選中", this.multipleSelection);
          // 取消當前行選中,清空保存的當前行數據
          this.$refs.cummonTable.setCurrent();
          this.multipleSelection = null;
        } else {
          this.multipleSelection = row;
          console.log(
            "點擊新行,選中并高亮該行,獲取當前行數據",
            this.multipleSelection
          );
        }
      }
    },

    //獲取表單組件傳遞的信息,此處接收的表單乃是數據表格對應的表單
    GetCondition(datas) {
      console.log("獲取form表單傳過來的數據=====:", datas);
      const param = datas;
      //獲取表單組件后,判斷是新增/修改
      if (this.dialogTitle.search("新增") != -1) {
        //調用新增方法
        this.InsertFormDatas(param);
      }
      if (this.dialogTitle.search("編輯") != -1) {
        this.InsertFormDatas(param);
      }
    },

    //#region  新增、編輯、刪除
    InsertFormDatas(data) {
      console.log("新增====", data);
      //轉換數據
      // data.dataId = parseInt(data.dataId);
      this.InsertOrUpdateBySysDictData(data);
    },
    // UpdateFormDatas(data) {
    //   // console.log("編輯====", data);
    //   this.updateApi(data);
    //   this.dialogVisible = false;
    // },
    DeleteFormDatas(data) {
      let _this = this;
      let param = { IDs: data.ID };
      console.log("刪除==", param);
      _this.$API.SysDictDataDelete(param).then((res) => {
        console.log(res, "調刪除接口");
        this.$message({
          message: "刪除成功!",
          type: "success",
        });
        let param = { DictID: this.selectedDictIDs };
        this.getTabledata(param);
      });
    },

    //#region 接口部分
    /**
     * 初始化表格數據
     * //根據左側樹形列表查詢對應的內容
     */
    getTabledata(param) {
      let _this = this;
      _this.tableData = [];
      console.log("傳給后端的數dicID", param);
      _this.$API.SysDictDataGetdata(param).then((res) => {
        let tempTable = res.data.data;
        console.log(_this.tableData, "表格==", res.data.data);
        if (tempTable != null) {
          tempTable.forEach((item) => {
            item.ID = item.Model.ID;
            item.ParentId = item.ParentId;
            item.DataID = item.Model.DataID;
            item.DataName = item.Model.DataName;
            item.SortID = item.Model.SortID;
            item.Dsc = item.Model.Dsc;
            item.DictID = item.Model.DictID;

            //使用遞歸  todo
            if (item.Children.length != 0) {
              item.Children.forEach((item) => {
                item.ID = item.Model.ID;
                item.ParentId = item.ParentId;
                item.DataID = item.Model.DataID;
                item.DataName = item.Model.DataName;
                item.SortID = item.Model.SortID;
                item.Dsc = item.Model.Dsc;
                item.DictID = item.Model.DictID;

                if (item.Children.length != 0) {
                  item.Children.forEach((item) => {
                    item.ID = item.Model.ID;
                    item.ParentId = item.ParentId;
                    item.DataID = item.Model.DataID;
                    item.DataName = item.Model.DataName;
                    item.SortID = item.Model.SortID;
                    item.Dsc = item.Model.Dsc;
                    item.DictID = item.Model.DictID;
                  });
                }
              });
            }
          });
          _this.tableData = tempTable;
        } else {
          _this.tableData = [];
        }
        if (res.data.code != 200) {
          this.$message({
            message: "沒有數據,請新增數據",
            type: "warning",
            showClose: true,
          });
        }
        console.log("表格數據", _this.tableData);
        // console.log("監聽父節點數據的變化1", _this.partend);
        _this.$refs.cummonTable.SettableData(_this.tableData);
      });
    },

    //新增同級或子級接口
    async InsertOrUpdateBySysDictData(data) {
      let _this = this;
      // console.log("新增成功", param);
      let param = data.Form; //表單的值
      _this.$API.SysDictDataAddandUpdate(param).then((res) => {
        console.log("成功調接口", res);
        if (res.data.msg == "字段已存在!") {
          this.$message.error("新增或刪除失敗,該字典名稱已存在!");
        } else {
          if (this.dialogTitle.search("新增") != -1) {
            this.$message({
              message: "新增成功!",
              type: "success",
            });
            if (data.dialogVisible == true) {
              this.dialogVisible = true;
              this.formID = res.data.data.ID;
            } else {
              this.dialogVisible = false;
            }
          } else {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            if (data.dialogVisible == true) {
              this.dialogVisible = true;
              this.formID = res.data.data.ID;
            } else {
              this.dialogVisible = false;
            }
          }
          let param = { DictID: this.selectedDictIDs };
          _this.getTabledata(param);
          this.$refs.cummonTable.setCurrent(); //取消選中數據
          this.multipleSelection = null; //選中的值為空
        }
      });
    },
    //#endregion

    //#endregion

    /**
     * 初始化左側樹
     * @param {*} GetDataLists
     */
    SetTreeDatas() {
      let _this = this;
      //重新渲染,itemKey用于處理Table不渲染的問題
      _this.itemKey = Math.random();
      //#region 假
      // let res = await fakeApi.dictTable();
      // GetDataLists = res.data;
      // this.treeData = GetDataLists;
      //#endregion
      _this.$API.SysDictDataGetLeftdata().then((res) => {
        _this.loading = false;
        _this.treeData = res.data.data;
        // console.log("左側樹==", res.data.data);
      });
    },

    /**
     * @GetColDataList: 初始化表頭
     */
    GetColDataList() {
      let _this = this;
      let param = this.btnData;
      _this.$API.GetFieldAuthorization(param).then((res) => {
        console.log(res, "調表頭接口111");
        let resData = res.data.data;
        let tempdata = [];
        resData.forEach((item) => {
          tempdata.push({ label: item.FieldDsc, prop: item.FieldName });
        });
        console.log("表頭字段11==", tempdata);
        _this.$refs.cummonTable.SetDataTableHeader(tempdata);
        this.$message({
          message: "成功!",
          type: "success",
        });
      });
    },

    //關閉模態框
    handleClose(done) {
      let _this = this;
      this.$confirm("尚未保存的內容會丟失,是否確定關閉?", "提示")
        .then((_) => {
          done();
          this.dialogVisible = false;
          let param = { DictID: this.selectedDictIDs };
          _this.getTabledata(param);
          this.$refs.cummonTable.setCurrent(); //取消選中數據
        })
        .catch((_) => {});
    },

    /**
     * 點擊取消 關閉form表單
     */
    GetcloseData(val) {
      this.dialogVisible = val;
      let param = { DictID: this.selectedDictIDs };
      this.getTabledata(param);
      this.$refs.cummonTable.setCurrent(); //取消選中數據
      this.multipleSelection = null; //選中的值為空
    },

    /**傳遞表頭
     * @MenuId:該菜單項id,
     * @FieldName:列頭名稱
     * @FieldDsc:列頭中文名稱
     */
    setHead() {
      //獲取菜單id進行傳參
      let MenuIDs = localStorage.getItem("MenuID");
      console.log(MenuIDs, "獲取數據字典的菜單id");
      let param = {
        MenuId: MenuIDs,
        FieldName: "DataName,SortID,Dsc,DataID",
        FieldDsc: "字典名稱,排序,備注,字典編號",
      };
      this.$API.RoleSetMenuField(param).then((res) => {
        console.log(res, "傳遞表頭");
      });
    },
  },
};
</script>

<style scoped>
.jbTypeStyle {
  /* background: linear-gradient(#00b7f9, #018ff2, #0165eb); */
  background: linear-gradient(147deg, #70c0ff, #2f9fff);
  color: #fff;
  /* border-radius: 5px; */
  height: 46px;
  width: 103%;
  /* padding: 3% 4%; */
  padding: 7% 26%;
  margin-bottom: 0%;
}

/**表格表頭背景色 */
.dictionaryIndex ::v-deep .el-table th,
::v-deep .el-table thead.is-group th.el-table__cell {
  background: linear-gradient(147deg, #70c0ff, #2f9fff);
  color: #fff;
  padding: 0;
  margin: 0;
}

.mainStyle {
  height: 100%;
  /* padding: 0 2%; */
}

.dictionaryIndex ::v-deep .el-tree-node {
  /* height: 40px; */
  padding: 2%;
}

/**選中節點,背景色 */
.dictionaryIndex
  ::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #ecf1ff;
  color: #4977fc;
  border-radius: 5px;
}

/**添加form 表單背景色 */
/* .dialogStyle >>> .el-dialog {
  background: url("../../../assets/imgList/userFormBG.jpg") no-repeat;
  background-position: center;
  background-size: 100% 100%;
} */
.custom_icon {
  background-image: url("../../../../assets/imgList/planIcon.png");
  background-size: cover;
  background-position: center;
  display: inline-block;
  width: 17px;
  height: 17px;
  vertical-align: middle;
}

.dic_btnStyle {
  padding: 0 0 1% 1%;
  float: right;
}
</style>


3.2?子組件
<template>
  <div class="DictForm">
    <!-- @change="newFrom" -->
    <el-form
      ref="newFrom"
      :form="form"
      :model="newFrom"
      :rules="rules"
      label-width="100px"
      style="padding-left: 7px"
    >
      <el-form-item
        label="父級名稱"
        prop="ParentID"
      >
        <el-select
          v-model="newFrom.ParentID"
          clearable
        >
          <!--            :label="item.Text" :value="item.ID"  input框顯示的值-->
          <el-option
            :key="newFrom.ParentID"
            :value="newFrom.ParentID"
            :label="newFrom.ParentName"
            placeholder="請選擇父節點"
            class="aa"
          >
            <el-tree
              :data="partendData"
              node-key="ID"
              :props="defaultProps"
              @node-click="handleNodeClick"
            ></el-tree>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="字典名稱"
        prop="DataName"
      >
        <el-input v-model="newFrom.DataName"></el-input>
      </el-form-item>

      <el-form-item
        label="排序"
        prop="SortID"
      >
        <el-input v-model="newFrom.SortID"></el-input>
      </el-form-item>
      <el-form-item label="備注">
        <el-input
          v-model="newFrom.Dsc"
          type="textarea"
          resize="none"
        ></el-input>
      </el-form-item>

      <el-form-item style="width: 91%;">
        <el-button
          type="primary"
          class="formBtn submit"
          @click="onSubmit('newFrom')"
        >保存</el-button>
        <el-button
          @click="onclose()"
          class="formBtn closeSub"
          style="right: -11%;"
        >保存并關閉</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// import formBtnStyle from "@/assets/css/formBtnStyle.css";

export default {
  props: ["form", "formID", "partend"],
  // components: { formBtnStyle },

  data() {
    let checkPriceSell = (rule, value, callback) => {
      if (value) {
        if (!/^\d+(\.\d{1,2})?$/.test(value)) {
          callback(new Error("請輸入數字!"));
        } else {
          callback();
        }
      }
    };
    return {
      newFrom: {
        DataName: "", //名稱
        ParentID: "", //父節點ID
        SortID: "", //排序
        Dsc: "", //備注
        DictID: "", //與左側關聯ID
        DataID: "", //字典編號
        ParentName: "", //父節點名稱
      },
      rules: {
        //驗證
        DataName: [
          {
            required: true,
            message: "請輸入字典名稱",
            trigger: "blur",
          },
        ],
        SortID: [
          {
            validator: checkPriceSell,
            required: true,
            trigger: ["blur", "change"],
          },
        ],
      },
      //#region 父節點
      //1. 接收父組件傳遞過來的父節點的值
      partendData: [],
      defaultProps: {
        children: "Children",
        label: "Text",
        id: "ID",
      },
      //#endregion
    };
  },
  created() {
    if (JSON.stringify(this.form) == "{}") {
      this.newFrom = {};
    } else {
      this.newFrom = this.form;
    }
  },
  watch: {
    form(newVal, oldVal) {
      if (newVal && newVal.length == 0) {
        this.newFrom = {};
      } else {
        this.newFrom = newVal;
      }
    },
    formID(n, o) {
      console.log("監聽ID的變化", n);
      this.newFrom.ID = n;
    },
    partend: {
      deep: true,
      immediate: true,
      handler(n, o) {
        this.partendData = n;
        console.log("監聽父節點數據的變化", n);
      },
    },
  },
  mounted() {
    console.log("接受父組件的值==form=====", this.form);
  },

  methods: {
    //保存
    onSubmit(newFrom) {
      this.$refs[newFrom].validate((valid) => {
        if (valid) {
          // 如果有值就傳給父組件
          console.log("保存this.newFrom===", this.newFrom);
          let paramForm = {
            Form: this.newFrom,
            dialogVisible: true,
          };
          this.$emit("fathernewFrom", paramForm); //把this.newFrom指傳給父組件
        } else {
          return false;
        }
      });
    },
    onclose() {
      let paramForm = {
        Form: this.newFrom,
        dialogVisible: false,
      };
      console.log("保存并關閉==", this.Form);
      this.$emit("fathernewFrom", paramForm);
    },
    // 點擊數
    handleNodeClick(val) {
      console.log(val, "zzzz");
      this.newFrom.ParentID = val.ID;
      this.newFrom.ParentName = val.Text;
      this.treeID = val.ID;
    },
  },
};
</script>
<style scoped>
@import "@/assets/css/formBtnStyle.css";

.aa {
  height: 10rem;
  overflow-y: scroll;
}
.DictForm ::v-deep .el-select {
  width: 100%;
}
</style>

原文鏈接:https://blog.csdn.net/CMDN123456/article/details/131540724

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新