el-tree 让已选择的节点后滚动到最顶部

<el-tree
            :empty-text="emptyText"
            id="filterTree"
            class="filter-tree"
            style="overflow:scroll; overflow-x: hidden;flex:1;"
            :style="{ height: tHeight - 60 + 'px' }"
            node-key="id"
            :data="orgTreeData"
            :props="defaultProps"
            @node-click="getNodeData"
            default-expand-all
            highlight-current
            ref="orgTree"
            :filter-node-method="filterNode"
          >
          </el-tree>

  

getTreeData() {
      this.emptyText = '数据加载中。。。';
      if (this.orgTreeData.length === 0) {
        projectDataAPI.listOrgTree().then(response => {
          this.orgTreeData = response.data;
          if (this.orgTreeData.length === 0) {
            this.emptyText = '暂无数据';
          }

      /**
       *下面的代码是核心代码 滚动到可见范围区 获取树的数据后让指定节点高亮 获取高亮节点距离父元素的顶部距离(offsetTop) 获得父容器的文档内容的高度(scrollHeight) 父容器的高度(clientHeight)
       *当offsetTop > clientHeight 将滚动条滚动到可见区域
       */

          this.$nextTick(async () => {
            await this.$refs.orgTree.setCurrentKey(this.projectId);
            let nodeOffsetTop = document.querySelector(
              '.filter-tree .is-current'
            ).offsetTop;
            let parentNodeClientHeight = document.querySelector('#filterTree')
              .clientHeight;
            let parentNodeScrollHeight = document.querySelector(
              '.filter-tree .el-tree-node'
            ).scrollHeight;
            if (nodeOffsetTop > parentNodeClientHeight) {
              document.querySelector('#filterTree').scrollTop =
                nodeOffsetTop - parentNodeClientHeight / 2;
            }
          });
        });
      }
    },

  

posted @ 2021-12-08 19:17  你丫才美工  阅读(1425)  评论(0编辑  收藏  举报