Vue 3 递归组件实战:自引用组件渲染无限层级树,配合惰性展开与事件冒泡

未来之星2026-11-1512 次阅读

无限层级的数据,模板写不出那么多层

组织架构、评论楼中楼、文件树、菜单权限,这类数据的共同点是层数由后端决定,编译期根本不知道有多深。手写三层 v-for 只能覆盖到第三层,第四层就悄悄丢了。Vue 组件可以在自己的模板里渲染自己,只要能拿到组件名,递归就有了落点。真正麻烦的从来不是递归本身,而是展开状态放在哪、事件怎么一层层往上传,以及深树下的渲染开销。

最小可运行的自引用组件

用 script setup 时,单文件组件的文件名就是组件名,TreeNode.vue 内部可以直接写 TreeNode 自引用,不需要额外注册。类型单独放 types.ts,避免在 script setup 里写导出语句。下面两段放进同一个目录就能跑,子节点只在自己被展开时才递归创建。

// types.ts
export interface TreeNode {
  id: string
  label: string
  children?: TreeNode[]
}

export const tree: TreeNode[] = [
  {
    id: '1',
    label: '研发中心',
    children: [
      { id: '1-1', label: '前端组' },
      {
        id: '1-2',
        label: '平台组',
        children: [{ id: '1-2-1', label: '基础架构' }],
      },
    ],
  },
  { id: '2', label: '设计中心' },
]
<!-- TreeNode.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import type { TreeNode } from './types'

const props = defineProps<{
  node: TreeNode
  depth?: number
}>()

const emit = defineEmits<{
  (e: 'select', id: string): void
}>()

const open = ref(false)
const hasChildren = () => !!props.node.children?.length
</script>

<template>
  <li>
    <button @click="hasChildren() ? (open = !open) : emit('select', node.id)">
      {{ node.label }}
    </button>
    <ul v-if="open && hasChildren()">
      <TreeNode
        v-for="child in node.children"
        :key="child.id"
        :node="child"
        :depth="(depth ?? 0) + 1"
        @select="emit('select', $event)"
      />
    </ul>
  </li>
</template>

外层这样挂载。注意事件要逐层转发,递归组件里子组件发出的事件不会自动穿过中间层,上面模板里的 @select 转发就是为了这个。

<!-- App.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import TreeNode from './TreeNode.vue'
import { tree } from './types'

const activeId = ref('')
function onSelect(id: string) {
  activeId.value = id
}
</script>

<template>
  <ul>
    <TreeNode
      v-for="node in tree"
      :key="node.id"
      :node="node"
      @select="onSelect"
    />
  </ul>
  <p>当前选中:{{ activeId || '无' }}</p>
</template>

展开状态放在组件内,还是上提到共享上下文

上面的写法把 open 放在每个节点实例里,卸载即丢失,胜在简单,但做不了「记住上次展开位置」或「全部展开」。要持久化就把展开集合提到父级,用一个 Set 存 id,通过 provide 注入,避免每层都透传一份 props。深层节点直接调共享方法,事件转发那堆样板也一并省掉。

// treeContext.ts
import { inject, provide, ref, type InjectionKey, type Ref } from 'vue'

export type TreeCtx = {
  expanded: Ref<Set<string>>
  toggle: (id: string) => void
  isOpen: (id: string) => boolean
}

export const treeKey: InjectionKey<TreeCtx> = Symbol('tree')

export function provideTree() {
  const expanded = ref(new Set<string>())
  const toggle = (id: string) => {
    const next = new Set(expanded.value)
    if (next.has(id)) {
      next.delete(id)
    } else {
      next.add(id)
    }
    expanded.value = next // 换引用,确保每次都触发更新
  }
  const isOpen = (id: string) => expanded.value.has(id)
  provide(treeKey, { expanded, toggle, isOpen })
}

export function useTree() {
  const ctx = inject(treeKey)
  if (!ctx) throw new Error('useTree 必须在 provideTree 下使用')
  return ctx
}

组件里把本地 open 换成共享状态即可,模板的判断条件跟着改。因为 Set 每次都整体替换引用,computed 和模板都能正确追踪到变化,不会出现改了集合但界面不动的情况。

<script setup lang="ts">
import { useTree } from './treeContext'
import type { TreeNode } from './types'

const props = defineProps<{ node: TreeNode }>()
const { isOpen, toggle } = useTree()
const hasChildren = () => !!props.node.children?.length
</script>

<template>
  <li>
    <button @click="toggle(node.id)">{{ node.label }}</button>
    <ul v-if="isOpen(node.id) && hasChildren()">
      <TreeNode v-for="c in node.children" :key="c.id" :node="c" />
    </ul>
  </li>
</template>

事件冒泡与深树的性能边界

事件种类超过两种时,逐层 emit 转发会变成维护负担,漏写一层就静默丢失,改成 provide 注入共享回调更稳。性能方面,用 v-if 控制展开天然只渲染可见分支,已经挡掉了大部分浪费;如果业务要求默认全展开几千个节点,就得换虚拟滚动,只挂载视口内的行。递归一定要有终止条件,children 为空或 undefined 时停止,别让判断写成恒真。

工程化注意点

  • 自引用依赖组件名,script setup 下用文件名即可;若用 defineOptions 显式命名,名字要与模板里的一致。
  • 递归必须有终止条件,children 为空或 undefined 时停止渲染,脏数据里的循环引用会让递归直接爆栈。
  • key 用业务 id,不要用 index;插入或删除节点时下标会变,Vue 会复用错误的组件实例导致展开状态串位。
  • 每层转发事件容易漏,事件种类超过两种就改用 provide 注入共享回调,让深层节点直接调外层方法。
  • 展开状态放组件内最轻,需要跨路由保持或做「全部展开」时再上提到 provide 的共享集合。
  • 老版本 Vue 里解构 defineProps 会丢失响应性,3.5 起官方支持响应式解构,团队版本不一致时统一用 props 访问最保险。
  • 数据来自后端时先做一次循环引用检测,并给超深层级设上限,避免一次响应把主线程卡住。
未

未来之星

文章作者

无限层级的数据,模板写不出那么多层 组织架构、评论楼中楼、文件树、菜单权限,这类数据的共同点是层数由后端决定,编译期根...

分类
技术
发布时间
2026-11-15
字数
约 4342 字
阅读
12 次