본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Tree

원문 보기 위키 갱신

Tree (트리 뷰)

Tree는 계층적 데이터 구조를 표시하고 상호작용할 수 있는 트리 뷰 컴포넌트예요. 파일 탐색기나 중첩 메뉴처럼 계층 구조를 보여줄 때 유용해요.

출처: Nuxt UI

본문

Tree 컴포넌트를 사용해 항목의 계층 구조를 표시할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree :items="items" />
</template>

항목 (Items)

items prop에 다음 속성들을 가진 객체 배열을 전달할 수 있어요:

  • icon?: string
  • label?: string
  • trailingIcon?: string
  • defaultExpanded?: boolean
  • disabled?: boolean
  • slot?: string
  • children?: TreeItem[]
  • onToggle?: (e: TreeItemToggleEvent<TreeItem>) => void
  • onSelect?: (e: TreeItemSelectEvent<TreeItem>) => void
  • class?: any
  • ui?: { item?: ClassNameValue, itemWithChildren?: ClassNameValue, link?: ClassNameValue, linkLeadingIcon?: ClassNameValue, linkLabel?: ClassNameValue, linkTrailing?: ClassNameValue, linkTrailingIcon?: ClassNameValue, listWithChildren?: ClassNameValue }

[!NOTE]

각 항목에는 고유 식별자가 필요해요. get-key가 제공되지 않으면 컴포넌트는 label prop을 식별자로 사용해요. 이상적으로는 고유 식별자를 반환하는 get-key 함수 prop을 제공해야 해요. 또는 labelKey prop을 사용해 어떤 속성을 고유 식별자로 쓸지 지정할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree :items="items" />
</template>

다중 선택 (Multiple)

multiple prop을 사용해 여러 항목을 선택할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree multiple :items="items" />
</template>

중첩 (Nested) 4.1+

nested prop을 사용해 Tree를 중첩 구조로 렌더링할지 평면 목록으로 렌더링할지 제어할 수 있어요. 기본값은 true예요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree :nested="false" :items="items" />
</template>

[!NOTE] 참고: #with-virtualization

nested가 false이면 모든 항목이 계층을 나타내는 들여쓰기와 함께 같은 레벨로 렌더링돼요. 이는 가상화(virtualization)나 드래그 앤 드롭 기능에 유용해요.

색상 (Color)

color prop을 사용해 Tree의 색상을 변경할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree color="neutral" :items="items" />
</template>

크기 (Size)

size prop을 사용해 Tree의 크기를 변경할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree size="xl" :items="items" />
</template>

끝 아이콘 (Trailing Icon)

trailing-icon prop을 사용해 부모 노드의 끝 Icon을 커스터마이즈할 수 있어요. 기본값은 i-lucide-chevron-down이에요.

[!NOTE]

항목에 아이콘이 지정되면 항상 이 prop들보다 우선해요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        trailingIcon: "i-lucide-chevron-down",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree trailing-icon="i-lucide-arrow-down" :items="items" />
</template>

Nuxt:

[!TIP] 참고: /docs/getting-started/integrations/icons/nuxt#theme

이 아이콘은 app.config.ts의 ui.icons.chevronDown 키 아래에서 전역적으로 커스터마이즈할 수 있어요.

Vue:

[!TIP] 참고: /docs/getting-started/integrations/icons/vue#theme

이 아이콘은 vite.config.ts의 ui.icons.chevronDown 키 아래에서 전역적으로 커스터마이즈할 수 있어요.

펼침 아이콘 (Expanded Icon)

expanded-icon과 collapsed-icon prop을 사용해 부모 노드가 펼쳐지거나 접혔을 때의 아이콘을 커스터마이즈할 수 있어요. 기본값은 각각 i-lucide-folder-open과 i-lucide-folder예요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app/",
    defaultExpanded: true,
    children: [
      {
        label: "composables/",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components/",
        defaultExpanded: true,
        children: [
          {
            label: "Card.vue",
            icon: "i-vscode-icons-file-type-vue"
          },
          {
            label: "Button.vue",
            icon: "i-vscode-icons-file-type-vue"
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree expanded-icon="i-lucide-book-open" collapsed-icon="i-lucide-book" :items="items" />
</template>

Nuxt:

[!TIP] 참고: /docs/getting-started/integrations/icons/nuxt#theme

이 아이콘들(ui.icons.folder와 ui.icons.folderOpen 키)은 app.config.ts에서 전역적으로 커스터마이즈할 수 있어요.

Vue:

[!TIP] 참고: /docs/getting-started/integrations/icons/vue#theme

이 아이콘들(ui.icons.folder와 ui.icons.folderOpen 키)은 vite.config.ts에서 전역적으로 커스터마이즈할 수 있어요.

비활성화 (Disabled)

disabled prop을 사용해 Tree와의 모든 사용자 상호작용을 막을 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = ref<TreeItem[]>([
  {
    label: "app",
    icon: "i-lucide-folder",
    defaultExpanded: true,
    children: [
      {
        label: "composables",
        icon: "i-lucide-folder",
        children: [
          {
            label: "useAuth.ts",
            icon: "i-vscode-icons-file-type-typescript"
          },
          {
            label: "useUser.ts",
            icon: "i-vscode-icons-file-type-typescript"
          }
        ]
      },
      {
        label: "components",
        icon: "i-lucide-folder",
        children: [
          {
            label: "Home",
            icon: "i-lucide-folder",
            children: [
              {
                label: "Card.vue",
                icon: "i-vscode-icons-file-type-vue"
              },
              {
                label: "Button.vue",
                icon: "i-vscode-icons-file-type-vue"
              }
            ]
          }
        ]
      }
    ]
  },
  {
    label: "app.vue",
    icon: "i-vscode-icons-file-type-vue"
  },
  {
    label: "nuxt.config.ts",
    icon: "i-vscode-icons-file-type-nuxt"
  }
])
</script>

<template>
  <UTree disabled :items="items" />
</template>

[!NOTE]

item.disabled를 사용해 개별 항목을 비활성화할 수도 있어요.

예제 (Examples)

선택 항목 제어하기 (Control selected item(s))

default-value prop이나 v-model 디렉티브를 사용해 선택된 항목을 제어할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items: TreeItem[] = [
  {
    label: 'app/',
    defaultExpanded: true,
    children: [
      {
        label: 'composables/',
        children: [
          { label: 'useAuth.ts', icon: 'i-vscode-icons-file-type-typescript' },
          { label: 'useUser.ts', icon: 'i-vscode-icons-file-type-typescript' }
        ]
      },
      {
        label: 'components/',
        defaultExpanded: true,
        children: [
          { label: 'Card.vue', icon: 'i-vscode-icons-file-type-vue' },
          { label: 'Button.vue', icon: 'i-vscode-icons-file-type-vue' }
        ]
      }
    ]
  },
  { label: 'app.vue', icon: 'i-vscode-icons-file-type-vue' },
  { label: 'nuxt.config.ts', icon: 'i-vscode-icons-file-type-nuxt' }
]

const value = ref()
</script>

<template>
  <UTree v-model="value" :items="items" />
</template>

[!TIP]

v-model이나 default-value가 제공될 때 각 항목에서 고유 키를 가져오는 함수를 변경하려면 get-key prop을 사용하세요.

항목이 선택되지 않도록 하려면 item.onSelect() 속성이나 전역 select 이벤트를 사용할 수 있어요:

<script setup lang="ts">
import type { TreeItemSelectEvent } from 'reka-ui'
import type { TreeItem } from '@nuxt/ui'

const items: TreeItem[] = [
  {
    label: 'app/',
    defaultExpanded: true,
    onSelect: (e: Event) => {
      e.preventDefault()
    },
    children: [
      {
        label: 'composables/',
        children: [
          { label: 'useAuth.ts', icon: 'i-vscode-icons-file-type-typescript' },
          { label: 'useUser.ts', icon: 'i-vscode-icons-file-type-typescript' }
        ]
      },
      {
        label: 'components/',
        defaultExpanded: true,
        children: [
          { label: 'Card.vue', icon: 'i-vscode-icons-file-type-vue' },
          { label: 'Button.vue', icon: 'i-vscode-icons-file-type-vue' }
        ]
      }
    ]
  },
  { label: 'app.vue', icon: 'i-vscode-icons-file-type-vue' },
  { label: 'nuxt.config.ts', icon: 'i-vscode-icons-file-type-nuxt' }
]

function onSelect(e: TreeItemSelectEvent<TreeItem>) {
  if (e.detail.originalEvent.type === 'click') {
    e.preventDefault()
  }
}
</script>

<template>
  <UTree :items="items" @select="onSelect" />
</template>

[!NOTE]

이렇게 하면 부모 항목을 선택하지 않고 펼치거나 접을 수 있어요.

펼침 항목 제어하기 (Control expanded items)

default-expanded prop이나 v-model 디렉티브를 사용해 펼쳐진 항목을 제어할 수 있어요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = [
  {
    label: 'app/',
    id: 'app',
    children: [
      {
        label: 'composables/',
        id: 'app/composables',
        children: [
          { label: 'useAuth.ts', icon: 'i-vscode-icons-file-type-typescript' },
          { label: 'useUser.ts', icon: 'i-vscode-icons-file-type-typescript' }
        ]
      },
      {
        label: 'components/',
        id: 'app/components',
        children: [
          { label: 'Card.vue', icon: 'i-vscode-icons-file-type-vue' },
          { label: 'Button.vue', icon: 'i-vscode-icons-file-type-vue' }
        ]
      }
    ]
  },
  { label: 'app.vue', id: 'app.vue', icon: 'i-vscode-icons-file-type-vue' },
  { label: 'nuxt.config.ts', id: 'nuxt.config.ts', icon: 'i-vscode-icons-file-type-nuxt' }
] satisfies TreeItem[]

const expanded = ref(['app', 'app/composables'])
</script>

<template>
  <UTree v-model:expanded="expanded" :items="items" :get-key="i => i.id" />
</template>

항목이 펼쳐지지 않도록 하려면 item.onToggle() 속성이나 전역 toggle 이벤트를 사용할 수 있어요:

<script setup lang="ts">
import type { TreeItemToggleEvent } from 'reka-ui'
import type { TreeItem } from '@nuxt/ui'

const items: TreeItem[] = [
  {
    label: 'app/',
    defaultExpanded: true,
    onToggle: (e: Event) => {
      e.preventDefault()
    },
    children: [
      {
        label: 'composables/',
        children: [
          { label: 'useAuth.ts', icon: 'i-vscode-icons-file-type-typescript' },
          { label: 'useUser.ts', icon: 'i-vscode-icons-file-type-typescript' }
        ]
      },
      {
        label: 'components/',
        defaultExpanded: true,
        children: [
          { label: 'Card.vue', icon: 'i-vscode-icons-file-type-vue' },
          { label: 'Button.vue', icon: 'i-vscode-icons-file-type-vue' }
        ]
      }
    ]
  },
  { label: 'app.vue', icon: 'i-vscode-icons-file-type-vue' },
  { label: 'nuxt.config.ts', icon: 'i-vscode-icons-file-type-nuxt' }
]

function onToggle(e: TreeItemToggleEvent<TreeItem>) {
  if (e.detail.originalEvent.type === 'keydown') {
    e.preventDefault()
  }
}
</script>

<template>
  <UTree :items="items" @toggle="onToggle" />
</template>

[!NOTE]

이렇게 하면 자식 항목을 펼치거나 접지 않고 부모 항목을 선택할 수 있어요.

항목에 체크박스 추가하기 (With checkbox in items) 4.1+

item-leading 슬롯을 사용해 항목에 Checkbox를 추가할 수 있어요. multiple, propagate-select, bubble-select prop을 사용해 부모-자식 관계의 다중 선택을 활성화하고, select와 toggle 이벤트로 항목의 선택·펼침 상태를 제어할 수 있어요.

<script setup lang="ts">
import type { TreeItemSelectEvent } from 'reka-ui'
import type { TreeItem } from '@nuxt/ui'

const items: TreeItem[] = [
  {
    label: 'app/',
    defaultExpanded: true,
    children: [
      {
        label: 'composables/',
        children: [
          { label: 'useAuth.ts' },
          { label: 'useUser.ts' }
        ]
      },
      {
        label: 'components/',
        defaultExpanded: true,
        children: [
          { label: 'Card.vue' },
          { label: 'Button.vue' }
        ]
      }
    ]
  },
  { label: 'app.vue' },
  { label: 'nuxt.config.ts' }
]

const value = ref<(typeof items)>([])

function onSelect(e: TreeItemSelectEvent<TreeItem>) {
  if (e.detail.originalEvent.type === 'click') {
    e.preventDefault()
  }
}
</script>

<template>
  <UTree
    v-model="value"
    :as="{ link: 'div' }"
    :items="items"
    multiple
    propagate-select
    bubble-select
    @select="onSelect"
  >
    <template #item-leading="{ selected, indeterminate, handleSelect }">
      <UCheckbox
        :model-value="indeterminate ? 'indeterminate' : selected"
        tabindex="-1"
        @change="handleSelect"
        @click.stop
      />
    </template>
  </UTree>
</template>

[!NOTE]

이 예제는 Checkbox도 button으로 렌더링되므로 as prop을 사용해 항목을 button에서 div로 변경해요.

드래그 앤 드롭 (With drag and drop) 4.1+

@vueuse/integrations의 useSortable 컴포저블을 사용해 Tree에 드래그 앤 드롭 기능을 활성화할 수 있어요. 이 통합은 Sortable.js를 감싸서 매끄러운 드래그 앤 드롭 경험을 제공해요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'
import { useSortable } from '@vueuse/integrations/useSortable'

const items = shallowRef<TreeItem[]>([
  {
    label: 'app/',
    defaultExpanded: true,
    children: [
      {
        label: 'composables/',
        children: [
          { label: 'useAuth.ts', icon: 'i-vscode-icons-file-type-typescript' },
          { label: 'useUser.ts', icon: 'i-vscode-icons-file-type-typescript' }
        ]
      },
      {
        label: 'components/',
        defaultExpanded: true,
        children: [
          { label: 'Card.vue', icon: 'i-vscode-icons-file-type-vue' },
          { label: 'Button.vue', icon: 'i-vscode-icons-file-type-vue' }
        ]
      }
    ]
  },
  { label: 'app.vue', icon: 'i-vscode-icons-file-type-vue' },
  { label: 'nuxt.config.ts', icon: 'i-vscode-icons-file-type-nuxt' }
])

function flatten(items: TreeItem[], parent = items): { item: TreeItem, parent: TreeItem[], index: number }[] {
  return items.flatMap((item, index) => [
    { item, parent, index },
    ...(item.children?.length && item.defaultExpanded ? flatten(item.children, item.children) : [])
  ])
}

function moveItem(oldIndex: number, newIndex: number) {
  if (oldIndex === newIndex) return

  const flat = flatten(items.value)
  const source = flat[oldIndex]
  const target = flat[newIndex]

  if (!source || !target) return

  const [moved] = source.parent.splice(source.index, 1)
  if (!moved) return

  const updatedFlat = flatten(items.value)
  const updatedTarget = updatedFlat.find(({ item }) => item === target.item)
  if (!updatedTarget) return

  const insertIndex = oldIndex < newIndex ? updatedTarget.index + 1 : updatedTarget.index
  updatedTarget.parent.splice(insertIndex, 0, moved)
}

const tree = useTemplateRef<HTMLElement>('tree')

useSortable(tree, items, {
  animation: 150,
  ghostClass: 'opacity-50',
  onUpdate: (e: any) => moveItem(e.oldIndex, e.newIndex)
})
</script>

<template>
  <UTree ref="tree" :nested="false" :unmount-on-hide="false" :items="items" />
</template>

[!NOTE]

이 예제는 항목을 드래그 앤 드롭할 수 있도록 nested prop을 false로 설정해 항목의 평면 목록을 만들어요.

가상화 (With virtualization) 4.1+

virtualize prop을 사용해 대규모 목록에 대한 가상화를 불리언이나 { estimateSize: 32, overscan: 12 } 같은 옵션 객체로 활성화할 수 있어요.

[!WARNING]

가상화를 활성화하면 nested prop을 false로 설정한 것과 유사하게 트리 구조가 평면화돼요.

<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items: TreeItem[] = Array(1000).fill(0).map((_, i) => ({
  label: `Item ${i + 1}`,
  children: [
    { label: `Child ${i + 1}-1`, icon: 'i-lucide-file' },
    { label: `Child ${i + 1}-2`, icon: 'i-lucide-file' }
  ]
}))
</script>

<template>
  <UTree virtualize :items="items" class="h-80" />
</template>

커스텀 슬롯 사용하기 (With custom slot)

slot 속성을 사용해 특정 항목을 커스터마이즈할 수 있어요.

다음 슬롯들에 접근할 수 있어요:

  • #{{ item.slot }}-wrapper
  • #{{ item.slot }}
  • #{{ item.slot }}-leading
  • #{{ item.slot }}-label
  • #{{ item.slot }}-trailing
<script setup lang="ts">
import type { TreeItem } from '@nuxt/ui'

const items = [
  {
    label: 'app/',
    slot: 'app' as const,
    defaultExpanded: true,
    children: [
      {
        label: 'composables/',
        children: [
          { label: 'useAuth.ts', icon: 'i-vscode-icons-file-type-typescript' },
          { label: 'useUser.ts', icon: 'i-vscode-icons-file-type-typescript' }
        ]
      },
      {
        label: 'components/',
        defaultExpanded: true,
        children: [
          { label: 'Card.vue', icon: 'i-vscode-icons-file-type-vue' },
          { label: 'Button.vue', icon: 'i-vscode-icons-file-type-vue' }
        ]
      }
    ]
  },
  { label: 'app.vue', icon: 'i-vscode-icons-file-type-vue' },
  { label: 'nuxt.config.ts', icon: 'i-vscode-icons-file-type-nuxt' }
] satisfies TreeItem[]
</script>

<template>
  <UTree :items="items">
    <template #app="{ item }">
      <p class="italic font-bold">
        {{ item.label }}
      </p>
    </template>
  </UTree>
</template>

API

Props

/**
 * Props for the Tree component
 */
interface TreeProps {
  /**
   * The element or component this component should render as.
   * @default 'ul'
   */
  as?: any;
  /**
   * @default 'primary'
   */
  color?: "primary" | "secondary" | "success" | "info" | "warning" | "error" | "neutral" | undefined;
  /**
   * @default 'md'
   */
  size?: "md" | "xs" | "sm" | "lg" | "xl" | undefined;
  /**
   * This function is passed the index of each item and should return a unique key for that item
   */
  getKey?: (val: T[number]): string | undefined;
  /**
   * The key used to get the label from the item.
   * @default 'label'
   */
  labelKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * The icon displayed on the right side of a parent node.
   * @default appConfig.ui.icons.chevronDown
   */
  trailingIcon?: any;
  /**
   * The icon displayed when a parent node is expanded.
   * @default appConfig.ui.icons.folderOpen
   */
  expandedIcon?: any;
  /**
   * The icon displayed when a parent node is collapsed.
   * @default appConfig.ui.icons.folder
   */
  collapsedIcon?: any;
  items?: T | undefined;
  /**
   * The controlled value of the Tree. Can be bind as `v-model`.
   */
  modelValue?: M extends true ? T[number][] : T[number] | undefined;
  /**
   * The value of the Tree when initially rendered. Use when you do not need to control the state of the Tree.
   */
  defaultValue?: M extends true ? T[number][] : T[number] | undefined;
  /**
   * Whether multiple options can be selected or not.
   */
  multiple?: M | undefined;
  /**
   * Use nested DOM structure (children inside parents) vs flattened structure (all items at same level).
   * When `virtualize` is enabled, this is automatically set to `false`.
   * @default true
   */
  nested?: boolean | undefined;
  /**
   * Enable virtualization for large lists.
   * Note: when enabled, the tree structure is flattened like if `nested` was set to `false`.
   * @default false
   */
  virtualize?: boolean | { overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; } | undefined;
  onSelect?: (e: SelectEvent<T[number]>, item: T[number]): void | undefined;
  onToggle?: (e: ToggleEvent<T[number]>, item: T[number]): void | undefined;
  ui?: { root?: SlotClass; item?: SlotClass; listWithChildren?: SlotClass; itemWithChildren?: SlotClass; link?: SlotClass; linkLeadingIcon?: SlotClass; linkLabel?: SlotClass; linkTrailing?: SlotClass; linkTrailingIcon?: SlotClass; } | undefined;
  /**
   * The controlled value of the expanded item. Can be binded with `v-model`.
   */
  expanded?: string[] | undefined;
  /**
   * The value of the expanded tree when initially rendered. Use when you do not need to control the state of the expanded tree
   */
  defaultExpanded?: string[] | undefined;
  /**
   * How multiple selection should behave in the collection.
   */
  selectionBehavior?: "toggle" | "replace" | undefined;
  /**
   * When `true`, selecting parent will select the descendants. Requires `multiple` to be `true`.
   */
  propagateSelect?: boolean | undefined;
  /**
   * When `true`, prevents the user from interacting with tree
   */
  disabled?: boolean | undefined;
  /**
   * When `true`, selecting children will update the parent state. Requires `multiple` to be `true`.
   */
  bubbleSelect?: boolean | undefined;
}

Slots

/**
 * Slots for the Tree component
 */
interface TreeSlots {
  item-wrapper(): any;
  item(): any;
  item-leading(): any;
  item-label(): any;
  item-trailing(): any;
}

Emits

/**
 * Emitted events for the Tree component
 */
interface TreeEmits {
  update:modelValue: (payload: [val: M extends true ? T[number][] : T[number]]) => void;
  update:expanded: (payload: [val: string[]]) => void;
}

테마 (Theme)

export default defineAppConfig({
  ui: {
    tree: {
      slots: {
        root: 'relative isolate',
        item: 'w-full',
        listWithChildren: 'border-s border-default',
        itemWithChildren: 'ps-1.5 -ms-px',
        link: 'relative group w-full flex items-center text-sm select-none before:absolute before:inset-y-px before:inset-x-0 before:z-[-1] before:rounded-md focus:outline-none focus-visible:outline-none focus-visible:before:outline-3',
        linkLeadingIcon: 'shrink-0 relative',
        linkLabel: 'truncate',
        linkTrailing: 'ms-auto inline-flex gap-1.5 items-center',
        linkTrailingIcon: 'shrink-0 transform transition-transform duration-200 ease-out motion-reduce:transition-none group-data-expanded:rotate-180'
      },
      variants: {
        virtualize: {
          true: {
            root: 'overflow-y-auto'
          }
        },
        color: {
          primary: {
            link: 'before:outline-primary/25'
          },
          secondary: {
            link: 'before:outline-secondary/25'
          },
          success: {
            link: 'before:outline-success/25'
          },
          info: {
            link: 'before:outline-info/25'
          },
          warning: {
            link: 'before:outline-warning/25'
          },
          error: {
            link: 'before:outline-error/25'
          },
          neutral: {
            link: 'before:outline-inverted/25'
          }
        },
        size: {
          xs: {
            listWithChildren: 'ms-4',
            link: 'px-2 py-1 text-xs gap-1',
            linkLeadingIcon: 'size-4',
            linkTrailingIcon: 'size-4'
          },
          sm: {
            listWithChildren: 'ms-4.5',
            link: 'px-2.5 py-1.5 text-xs gap-1.5',
            linkLeadingIcon: 'size-4',
            linkTrailingIcon: 'size-4'
          },
          md: {
            listWithChildren: 'ms-5',
            link: 'px-2.5 py-1.5 text-sm gap-1.5',
            linkLeadingIcon: 'size-5',
            linkTrailingIcon: 'size-5'
          },
          lg: {
            listWithChildren: 'ms-5.5',
            link: 'px-3 py-2 text-sm gap-2',
            linkLeadingIcon: 'size-5',
            linkTrailingIcon: 'size-5'
          },
          xl: {
            listWithChildren: 'ms-6',
            link: 'px-3 py-2 text-base gap-2',
            linkLeadingIcon: 'size-6',
            linkTrailingIcon: 'size-6'
          }
        },
        selected: {
          true: {
            link: 'before:bg-elevated'
          }
        },
        disabled: {
          true: {
            link: 'cursor-not-allowed opacity-75'
          }
        }
      },
      compoundVariants: [
        {
          color: 'primary',
          selected: true,
          class: {
            link: 'text-primary'
          }
        },
        {
          color: 'secondary',
          selected: true,
          class: {
            link: 'text-secondary'
          }
        },
        {
          color: 'success',
          selected: true,
          class: {
            link: 'text-success'
          }
        },
        {
          color: 'info',
          selected: true,
          class: {
            link: 'text-info'
          }
        },
        {
          color: 'warning',
          selected: true,
          class: {
            link: 'text-warning'
          }
        },
        {
          color: 'error',
          selected: true,
          class: {
            link: 'text-error'
          }
        },
        {
          color: 'neutral',
          selected: true,
          class: {
            link: 'text-highlighted'
          }
        },
        {
          selected: false,
          disabled: false,
          class: {
            link: [
              'hover:text-highlighted hover:before:bg-elevated/50',
              'transition-colors before:transition-colors'
            ]
          }
        }
      ],
      defaultVariants: {
        color: 'primary',
        size: 'md'
      }
    }
  }
})

변경 로그 (Changelog)

컴포넌트와 테마의 커밋 기록을 확인해 보세요.

더 알아보기 (Learn more)