指南

受控状态与方法

受控/非受控的判定规则、通过 ref 调用的方法与事件回调签名

判定规则

写法结果
不传 expanded-keys / current-key非受控,组件自己管状态,default-* 决定初始值
传 v-model:expanded-keys / v-model:current-key受控:值即状态,用户操作通过 update:* 回写,你改回去就生效
只传值、不监听 update:*锁定态:用户点 ± 或选节点看起来没反应,外部改值仍生效

受控与判定都只看 !== undefined(OkrTree.vue:394-395),所以传空数组就是「全部收起」而不是「不干预」。两者都需要 node-key。

非受控下 default-expanded-keys 与 default-checked-keys 的运行时语义不同(一个只追加、一个先清空再应用),见需要注意的行为。

通过 ref 调方法

受控状态与方法(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>
显示代码
App.vue
<script setup lang="ts">
import { ref } from 'vue'
import { VueOkrTree, type VueOkrTreeInstance, type TreeKey } from 'vue3-okr-tree'

const tree = ref<VueOkrTreeInstance | null>(null)
const expandedKeys = ref<TreeKey[]>([1])

tree.value?.expandAll()
tree.value?.scrollToNode(8) // Promise<boolean>,先展开祖先再滚动
</script>

定位类入参普遍接受三种形态:key、data 对象、内部 Node 实例(getNode / setCurrentKey / expandNode / remove / moveNode 等)。未配 node-key 时只有 Node 实例这一路可用,见需要注意的行为。

事件回调

node-click / node-expand / node-collapse / node-contextmenu 四个基础事件,加 check / check-change(复选框)与六个拖拽事件,再加两个受控回写 update:expandedKeys / update:currentKey。回调里的 node 一律是内部 Node 实例(源数据在 node.data),不是源数据对象;node-contextmenu 只有在你绑了它之后才阻止浏览器默认菜单。逐个签名见 API,用例见 Demo 总览。

Copyright © 2026