element-ui中tree树形组件 通过搜索定位到对应的树节点,并展示在可见区

发布时间 2023-06-05 18:02:50作者: 当下是吾

通过输入树节点名称定位到对应的树节点上,并显示在可见区域

 

<el-tree
      ref="tree"
      v-loading="treeLoading"
      :data="treeData"
      :props="treeProps"
      node-key="id"
      :expand-on-click-node="false"
      :highlight-current="true"
      :filter-node-method="filterNode"
      :default-expanded-keys="expandedKeys"
      :render-after-expand="false"
      @node-click="handleNodeClick">
         <span
            slot-scope="{ node, data }"
            class="custom-tree-node"
          >
            <span :id="data.id">{{ node.label }}</span> // 通过自定义节点,给每个节点一个id
          </span>
        </el-tree>

在选中对应的名称是定位到树节点上

selectedRegion(item) {
      if (Object.keys(item).length === 0) {
        return
      }
      this.expandedKeys.push(item.parentId)
      this.$refs.tree.setCurrentKey(item.regionId)       //通过 key 设置某个节点的当前选中状态,使用此方法必须设置 node-key 属性
      const node = document.getElementById(item.regionId) // 通过Id获取到对应的dom元素
      setTimeout(() => {
        if (node) {
          this.$nextTick(() => {
            node.scrollIntoView({ block: 'center' }) // 通过scrollIntoView方法将对应的dom元素定位到可见区域 【block: 'center'】这个属性是在垂直方向居中显示
         })
        }
      }, 100)

下面的内容来自 https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView 有兴趣的可以看看
Element 接口的scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见

element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型参数
element.scrollIntoView(scrollIntoViewOptions); // Object型参数

alignToTop可选
一个Boolean值:
如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。相应的 scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是这个参数的默认值。
如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐。相应的scrollIntoViewOptions: {block: "end", inline: "nearest"}。

scrollIntoViewOptions 可选
一个包含下列属性的对象:
behavior 可选
定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"。
block 可选
定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"。
inline 可选
定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"。