el-tree 節點動態查找

更新:樹的查詢組件。(以爲原來好傻逼)
1效果圖
未查找時:
image.png
查找時:
image.png
2代碼css

<template>
  <div
    style="height: 100%;"
    class="bd"
  >
    <div
      class="padding-gutter"
      style="height: 45px;"
    >
      <el-input
        v-model="searchInput"
        :disabled="btnDisable" 
        class="width-full"
        suffix-icon="el-icon-search"
        placeholder="請輸入查找內容"
        size="mini"
      />
    </div>
    <div style="overflow:auto;height:calc( 100% - 55px )">
      <el-tree
          ref="usertree"
          :data="data"
          :default-expanded-keys="expandKeys"
          :node-key="treeProps.idKey"
          :highlight-current="true"
          render-after-expand
          class="g-mnc"
          :filter-node-method="filterNode"
          :props="treeProps"
          @current-change="currentChange"
        />

    </div>

  </div>
</template>

<script>
import Bus from '.././assets/bus'
import { Message } from 'element-ui'
import { MessageBox } from 'element-ui'
import {transformTree2Array} from '../../common/js/util'
//import { returnChildDataByPar } from '.././ipUtil.js'

export default {
  name: "TreeApp",
  props:{
    data: {
      type: Array,
    },
    mode: String,
    props: {
      type: Object,
      default() {
        return {}
      }
    },
    btnDisable:Boolean,//true:修改狀態
    hasModify:Boolean,//頁面內容是否已修改 true:已修改
  },
  // props:['btnDisable','treeUserData','treeUserDataBack'],
  data() {
    return {
      loading: false,
      searchInput: '', // 樹過濾關鍵字
      treeProps: {
        children: 'zones',
        label: 'code_name',
        isLeaf: 'leaf',
        idKey: 'chr_id',
        // isLeaf: 'isLeaf'
      },
      expandAll: false,   
      oldKey:'',        
    };
  },
  computed: {
    expandKeys() {
      let list = transformTree2Array(this.data)
      if (list.length > 400) {
        list = this.data[0].children
      }
      return list.filter(item => item[this.treeProps.idKey]).map(item => item[this.treeProps.idKey])
    },
  },
  watch: {
    searchInput(val) {
      //if(val){
      this.$refs.usertree.filter(val);
      //}
    },
    props: {
      immediate: true,
      handler(obj) {
        this.treeProps = {...this.treeProps, ...obj}
      }
    },
    data(val) {
      this.loading = false
    },
  },
  methods: {
    // handleNodeClick(nodeInfo) {
    //   Bus.$emit('nodeInfo', nodeInfo);
    //   this.$emit('refreshData',nodeInfo);
    // },
    filterNode(val, data) {
      if (!val) return true;
      return [data[this.treeProps.label], data.py || '', data.pinyin || ''].some(item => item.indexOf(val) !== -1)
    },
    currentChange(data,node) {
      let vm = this
      if(this.btnDisable && this.hasModify ){//
        MessageBox.confirm('修改的內容未保存, 是否繼續切換?', '提示', {
          confirmButtonText: '肯定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vm.refresh(data)
        }).catch(() => {
          vm.$refs.usertree.setCurrentKey(vm.oldKey)
        });
      }else{
        this.refresh(data)
      }
    },
    refresh(data){
      this.oldKey = data.chr_id
      Bus.$emit('nodeInfo', data);
      this.$emit('refreshData',data);
    },
  }
}

    
</script>

<style  lang="scss" scoped>
@import "../../common/styles/variables";
  .el-tree{
    background-color: transparent
  }
  .padding-gutter{
    padding-top: $gutter ;
    padding-bottom: $gutter ;
    padding-left: $gutter ;
    /*padding: $gutter 0 px;*/
  }
  .border-grey{
    border: 1px #ccc solid;
  }
  .el-button+.el-button {
    margin-left: 0px;
  }
  .el-input--mini .el-input__inner{
    height: 28px !important;
  }
    .relative{
      position: relative;
    }
    .zhezhao{
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 1;
      width: 21%;
    }
    .display-none{
      display: none;
    }
    .display-block{
      display: none;
    }
</style>

=================================html

1.效果圖
經過在input框裏輸入值,動態查詢樹節點。將父節點展開,找到的節點顯示在最當前窗口。node

image.png

2.代碼element-ui

2.1 htmlui

<template>
    <div style="height: 100%; ">
        <div   style="height: 45px;padding-top:8px;padding-bottom:8px;">
            <el-label>快速查詢 :</el-label>
            <el-input 
                 style=" width: calc(100% - 210px);height: 28px !important;line-height: 28px !important;"
                 placeholder="請查找輸入內容" 
                v-model="searchInput" 
                @keyup.native="search">//按鍵結束就觸發,下面的查找按鈕其實能夠刪除
            </el-input>
            <el-button size="mini"  type="primary" @click.native="search">查找</el-button>
            <el-button size="mini"  type="" @click.native="next" style="margin-top: 0px">下一個</el-button>
        </div>

        <div 
              id="searchtree-eletree" //id便於定位
              style="height: calc(100% - 46px); overflow: auto;" class="border-grey">
            <el-tree :data="searchTreeDT"  
                             node-key="id" 
                             ref="tree" 
                            :highlight-current="true" 
                             expand-on-click-node
                            :props="defaultProps" 
                            :default-expanded-keys="defaultEexpandedkeys" //  展開節點
                            >
            </el-tree>
        </div>

    </div>
</template>

2.2 jsthis

<script>
    export default {
        data() {
            return {
                //樹
                searchTreeData:[],   
                defaultEexpandedkeys: [0],  //默認展開一級樹節點        
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                //查詢欄
                searchInput: '',
                searchIndex: null,
                searchData: [], 
            };
        },
        watch: {
            // 搜索框中內容變化,重置當前搜索結果的索引值
            searchInput: function () {
                this.searchIndex = null
            },
        },
        methods: {
            //查詢
            search() {
                this.searchIndex = null;
                if (this.searchInput) {
                    let searchInput = this.searchInput;
                    this.searchData = this.searchTreeData.filter( function(item) { 
                          return item.name.indexOf(searchInput) > -1 //返回符合查詢條件的節點
                    });
                    if (this.searchData.length) {//存在符合查詢條件的節點
                        this.searchIndex = 0;
                        //展開符合條件節點的父節點(使查詢節點顯示出來)
                        this.defaultEexpandedkeys = getParentsId(this.searchData[0], this.searchTreeData, 'id','pId', 0);
               
                        this.$nextTick(() => {//顯示完成後執行
                            this.$refs.tree.setCurrentKey(this.searchData[0].id);//高亮查詢到的第一個節點
                            setTimeout(() => {  
                                //根據樹id 找到高亮的節
                                let node = document.querySelector('#searchtree-eletree .is-current');點
                                if (node) {
                                    setTimeout(() => {
                                        // node.scrollIntoView(); //有bug,可嘗試
                                        let top = $(node).position().top;
                                        //關鍵代碼,將選中節點顯示在當前窗口可視區域
                                        $("#searchtree-eletree").scrollTop(top);
                                    }, 500);
                                }
                            }, 0);
                        }); 
                    } else {
                        //Message須要引入  import {Message} from 'element-ui'
                        Message.info('未找到任何匹配數據!'); 
                    }
                } else {
                    Message.info('請輸入要查找的內容!');
                }
            },
            next(){
                if (this.searchIndex !== null) {
                    this.searchIndex += 1;
                    this.searchIndex = this.searchIndex < this.searchData.length ? this.searchIndex : 0;
                    this.defaultEexpandedkeys = getParentsId(this.searchData[this.searchIndex], this.searchTreeData, 'id','pId', 0);
                    this.$nextTick(() => {
                        this.$refs.tree.setCurrentKey(this.searchData[this.searchIndex].id);
                        setTimeout(() => {  
                        let node = document.querySelector('#searchtree-eletree .is-current');
                        if (node) {
                            setTimeout(() => {
                            // node.scrollIntoView();
                            let top = $(node).position().top;
                            $("#searchtree-eletree").scrollTop(top);
                            }, 500);
                        }
                        }, 0);              
                    }); 
                } else {
                    if (this.searchInput) {
                        this.search();
                    } else {
                         Message.info('請輸入要查找的內容!');
                    }
                }
            },
        }
    }
</script>

2.3 在2.2 用到的獲取父節點id的方法spa

/**
 * 找到當前節點的全部祖先節點的idKey
 * @param {Object} node 當前節點信息
 * @param {Array} data 全部節點的數據信息
 * @returns {Array} parentsId 祖先節點的idKey
 */
export function getParentsId(node, data = [], idKey='id', pIdKey='pid', rootId = '0', parentsId = [] ){      
  if(!node) return [rootId, ...parentsId]; 
  if(node[pIdKey] == rootId) return [node[pIdKey], ...parentsId];
  let pNode = data.filter(item => item[idKey] == node[pIdKey]);   
  if(!pNode.length) return parentsId;
  parentsId.push(pNode[0][idKey]);
  return getParentsId(pNode[0], data, idKey, pIdKey, rootId, parentsId);      
};
相關文章
相關標籤/搜索