element-ui的下拉樹實現


來自博客園的這篇文章

我稍微改了以下,原文如果在外面設置了初始值的話,打開樹再關閉樹時,之前傳的值就沒了

<!-- 樹狀選擇器 -->
<template>
  <el-popover
    ref="popover"
    placement="bottom-start"
    trigger="click"
    @show="onShowPopover"
    @hide="onHidePopover"
  >
    <el-tree
      ref="tree"
      class="select-tree"
      highlight-current
      :style="`min-width: ${treeWidth}`"
      :data="data"
      :props="props"
      :node-key="props.nodeKey"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :default-expand-all="false"
      @node-click="onClickNode"
    ></el-tree>
    <el-input
      slot="reference"
      ref="input"
      v-model="labelModel"
      clearable
      :style="`width: ${width}px`"
      :class="{ 'rotate': showStatus }"
      suffix-icon="el-icon-arrow-down"
      :placeholder="placeholder"
    ></el-input>
  </el-popover>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    // 接收綁定參數
    value: String,
    // 輸入框寬度
    width: String,
    // 選項數據
    treeData: {
      type: Array,
      required: true
    },
    // 輸入框占位符
    placeholder: {
      type: String,
      required: false,
      default: "請選擇"
    },
    // 樹節點配置選項
    props: {
      type: Object,
      required: false,
      default: () => ({
        parent: "parentCode",
        value: "code",
        label: "name",
        children: "children",
        nodeKey: "code"
      })
    }
  },
  // 設置綁定參數
  model: {
    prop: "value",
    event: "selected"
  },
  computed: {
    // 是否為樹狀結構數據
    dataType() {
      const jsonStr = JSON.stringify(this.treeData);
      return jsonStr.indexOf(this.props.children) !== -1;
    },
    // 若非樹狀結構,則轉化為樹狀結構數據
    data() {
      return this.dataType ? this.treeData : this.switchTree();
    }
  },
  watch: {
    labelModel(val) {
      if (!val) {
        this.valueModel = "";
      }
      this.$refs.tree.filter(val);
    },
    value(val) {
      //console.log("val:" + val);
      if (!val || val === "0") {
        this.labelModel = "";
        this.valueModel = "";
        this.$refs.tree.setCurrentKey(null);
      } else {
        this.labelModel = this.queryTree(this.data, val);
        this.$refs.tree.setCurrentKey(val);
        this.valueModel = val;
      }
    }
  },
  data() {
    return {
      // 樹狀菜單顯示狀態
      showStatus: false,
      // 菜單寬度
      treeWidth: "auto",
      // 輸入框顯示值
      labelModel: "",
      // 實際請求傳值
      valueModel: "0"
    };
  },
  created() {
    // 檢測輸入框原有值並顯示對應 label
    if (this.value) {
      this.valueModel = this.value;
      this.labelModel = this.queryTree(this.data, this.value);
    }
    // 獲取輸入框寬度同步至樹狀菜單寬度
    this.$nextTick(() => {
      this.treeWidth = `${(this.width ||
        this.$refs.input.$refs.input.clientWidth) - 24}px`;
      if (this.value) {
        this.$refs.tree.setCurrentKey(this.value);
      }
    });
  },
  methods: {
    // 單擊節點
    onClickNode(node) {
      this.labelModel = node[this.props.label];
      this.valueModel = node[this.props.value];
      this.onCloseTree();
    },
    // 偏平數組轉化為樹狀層級結構
    switchTree() {
      return this.cleanChildren(this.buildTree(this.treeData, "0"));
    },
    // 隱藏樹狀菜單
    onCloseTree() {
      this.$refs.popover.showPopper = false;
    },
    // 顯示時觸發
    onShowPopover() {
      this.showStatus = true;
      this.$refs.tree.filter(false);
    },
    // 隱藏時觸發
    onHidePopover() {
      //console.log("valuemodel:" + this.valueModel);
      this.showStatus = false;
      this.$emit("selected", this.valueModel);
    },
    // 樹節點過濾方法
    filterNode(query, data) {
      if (!query) return true;
      return data[this.props.label].indexOf(query) !== -1;
    },
    // 搜索樹狀數據中的 ID
    queryTree(tree, id) {
      let stark = [];
      stark = stark.concat(tree);
      while (stark.length) {
        const temp = stark.shift();
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children]);
        }
        if (temp[this.props.value] === id) {
          return temp[this.props.label];
        }
      }
      return "";
    },
    // 將一維的扁平數組轉換為多層級對象
    buildTree(data, id = "0") {
      const fa = parentId => {
        const temp = [];
        for (let i = 0; i < data.length; i++) {
          const n = data[i];
          if (n[this.props.parent] === parentId) {
            n.children = fa(n.rowGuid);
            temp.push(n);
          }
        }
        return temp;
      };
      return fa(id);
    },
    // 清除空 children項
    cleanChildren(data) {
      const fa = list => {
        list.map(e => {
          if (e.children.length) {
            fa(e.children);
          } else {
            delete e.children;
          }
          return e;
        });
        return list;
      };
      return fa(data);
    }
  }
};
</script>

<style>
.el-input.el-input--suffix {
  cursor: pointer;
  overflow: hidden;
}
.el-input.el-input--suffix.rotate .el-input__suffix {
  transform: rotate(180deg);
}
.select-tree {
  max-height: 350px;
  overflow-y: scroll;
}
/* 菜單滾動條 */
.select-tree::-webkit-scrollbar {
  z-index: 11;
  width: 6px;
}
.select-tree::-webkit-scrollbar-track,
.select-tree::-webkit-scrollbar-corner {
  background: #fff;
}
.select-tree::-webkit-scrollbar-thumb {
  border-radius: 5px;
  width: 6px;
  background: #b4bccc;
}
.select-tree::-webkit-scrollbar-track-piece {
  background: #fff;
  width: 6px;
}
</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM