Skip to content

受控状态与方法

expanded-keys / current-key 传入后即为受控模式(需 node-key):列表内节点展开、其余收起;用户点击 +/- 或调用展开/收起方法都会触发 update:expandedKeys / update:currentKey 回写。不传时保持原版的非受控行为。

内置方法:expandAll / collapseAll / expandNode / collapseNode / scrollToNode / getNodeEl 等,完整列表见 API

受控状态与方法(1.2.0 新增)

v-model:expanded-keys / v-model:current-key 双向绑定展开态与选中态; 配合 expandAll / collapseAll / expandNode / collapseNode / scrollToNode 方法,以及 #expand-btn 插槽。

expandedKeys:[1]currentKey:null
expanded-keys 传入后为受控模式:列表内节点展开、其余收起,点击 +/- 或调用展开/收起方法都会触发 update:expandedKeys 回写;未传时保持原版非受控行为。 current-key 同理,null 表示无选中。两者都需要 node-key#expand-btn 插槽参数为 { node, data, expanded, side }show-node-num 开启时数字优先。
<template>
  <button @click="tree.expandAll()">expandAll()</button>
  <button @click="tree.collapseAll()">collapseAll()</button>
  <button @click="tree.expandNode(5)">expandNode(5)</button>
  <button @click="tree.scrollToNode(8)">scrollToNode(8)</button>

  <vue-okr-tree
    ref="tree"
    v-model:expanded-keys="expandedKeys"
    v-model:current-key="currentKey"
    :data="testData"
    direction="horizontal"
    show-collapsable
    node-key="id"
  >
    <!-- 自定义展开按钮:side 为 'left' | 'right',expanded 为该侧当前是否展开 -->
    <template #expand-btn="{ expanded, side }">
      <span class="org-chart-node-btn-text">{{ expanded ? '−' : '+' }}</span>
    </template>
  </vue-okr-tree>
</template>

<script setup>
import { ref } from 'vue'
import { VueOkrTree } from 'vue3-okr-tree'

const tree = ref(null)
const expandedKeys = ref([1])   // 受控:只展开 id 为 1 的根节点
const currentKey = ref(null)    // 受控:无选中
const testData = ref([{
  id: 1, label: 'xxx科技有有限公司',
  children: [{
    id: 2, label: '产品研发部',
    children: [{ id: 3, label: '研发-前端' }, { id: 4, label: '研发-后端' }, { id: 5, label: 'UI 设计' }]
  }, {
    id: 6, label: '销售部',
    children: [{ id: 7, label: '销售一部' }, { id: 8, label: '销售二部' }]
  }, {
    id: 9, label: '财务部'
  }]
}])
</script>
显示代码

基于 MIT 许可发布