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

ContentSearch

원문 보기 위키 갱신

ContentSearch (콘텐츠 검색)

ContentSearch는 문서 사이트에 바로 추가할 수 있는 CommandPalette예요. @nuxt/content와 연동된 검색으로 문서를 빠르게 찾을 수 있게 해 줘요.

출처: Nuxt UI

본문

[!WARNING] 참고: /docs/getting-started/integrations/content

이 컴포넌트는 @nuxt/content 모듈이 설치된 경우에만 사용할 수 있어요.

사용법 (Usage)

ContentSearch 컴포넌트는 CommandPalette 컴포넌트에 내장된 @nuxt/content 검색 지원, 내비게이션 그룹화, 컬러 모드 명령을 더한 확장이에요. 클라이언트 측 Fuse.js 필터링과 서버 측 FTS5 전문 검색을 모두 지원해요. icon, placeholder 등 어떤 CommandPalette 속성이든 전달할 수 있어요.

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

const { data: files } = useLazyAsyncData('content-search-example', () => queryCollectionSearchSections('docs', {
  ignoredTags: ['style']
}), {
  server: false
})

const navigation = inject<Ref<ContentNavigationItem[]>>('navigation')

const searchTerm = ref('')
</script>

<template>
  <ClientOnly>
    <LazyUContentSearch
      v-model:search-term="searchTerm"
      open
      :autofocus="false"
      :files="files"
      :navigation="navigation"
      :fuse="{ resultLimit: 42 }"
    />
  </ClientOnly>
</template>

[!NOTE]

Meta K를 누르거나 ContentSearchButton 컴포넌트, 혹은 useContentSearch 컴포저블을 사용해 CommandPalette를 열 수 있어요: const { open } = useContentSearch().

[!TIP]

서버에서 렌더링되지 않도록 ContentSearch 컴포넌트를 ClientOnly 컴포넌트로 감싸는 것이 좋아요.

내비게이션 (Navigation)

navigation prop을 queryCollectionNavigation과 함께 사용해 검색 결과를 섹션별로 그룹화할 수 있어요:

<script setup lang="ts">
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('content'))
</script>

<template>
  <UApp>
    <ClientOnly>
      <LazyUContentSearch
        :navigation="navigation"
      />
    </ClientOnly>
  </UApp>
</template>

파일 (Files)

files prop을 queryCollectionSearchSections와 함께 사용해 모든 검색 섹션을 미리 로드하고 클라이언트 측 Fuse.js 필터링을 사용할 수 있어요:

<script setup lang="ts">
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('content'))

const { data: files } = useLazyAsyncData('search', () => queryCollectionSearchSections('docs', {
  ignoredTags: ['style']
}), {
  server: false
})
</script>

<template>
  <UApp>
    <ClientOnly>
      <LazyUContentSearch
        :navigation="navigation"
        :files="files"
        :fuse="{ resultLimit: 20, fuseOptions: { threshold: 0.2 } }"
      />
    </ClientOnly>
  </UApp>
</template>

[!TIP]

fuse prop을 사용해 내부 CommandPalette에 전달되는 useFuse 옵션을 설정할 수 있어요. 예: resultLimit(기본 12), fuseOptions.threshold(기본 0.1).

검색 (Search) 4.8+

search prop을 useSearchCollection과 함께 사용하면 클라이언트 측 필터링 대신 하이라이트된 스니펫과 함께 서버 측 FTS5 전문 검색을 사용할 수 있어요:

[!WARNING]

@nuxt/content v3.14 이상이 필요해요.

<script setup lang="ts">
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('content'))

const { search, status, init } = useSearchCollection('content', {
  immediate: false,
  ignoredTags: ['style']
})

const { open } = useContentSearch()

// Defer index initialization until the user opens the palette when using `immediate: false`
watch(open, (value) => {
  if (value && status.value === 'idle') {
    init()
  }
})
</script>

<template>
  <UApp>
    <ClientOnly>
      <LazyUContentSearch
        :navigation="navigation"
        :search="search"
        :search-status="status"
      />
    </ClientOnly>
  </UApp>
</template>

[!TIP]

search-status를 전달하면 인덱스가 준비되면 컴포넌트가 자동으로 검색을 다시 트리거해요. search-delay(기본 100ms)를 사용해 검색을 실행하기 전에 입력을 멈춰야 하는 시간을 조절할 수 있어요. fuse.resultLimit 옵션은 모든 그룹(검색 결과, 링크, 테마 등)에서 반환되는 전체 결과 수를 제한해요.

[!NOTE]

search prop을 사용할 때는 files를 전달할 필요 없어요. 컴포넌트는 Fuse.js 대신 키 입력마다 비동기 검색 함수를 호출해요. 결과는 내비게이션별로 자동 매핑·그룹화되고 하이라이트 스니펫이 포함돼요. 모든 검색 섹션을 미리 로드해 입력 전에 내비게이션 항목을 탐색할 수 있는 files 방식과 달리, search prop은 쿼리를 입력한 후에만 결과를 반환해요.

단축키 (Shortcut)

shortcut prop을 사용해 ContentSearch 컴포넌트를 여는 defineShortcuts의 단축키를 변경할 수 있어요. 기본값은 meta_k(Meta K)예요.

<template>
  <UApp>
    <ClientOnly>
      <LazyUContentSearch
        shortcut="meta_k"
      />
    </ClientOnly>
  </UApp>
</template>

links prop을 사용해 커맨드 팔레트 맨 위에 빠른 접근 링크 그룹을 추가할 수 있어요:

<script setup lang="ts">
const links = [{
  label: 'Docs',
  icon: 'i-lucide-book',
  to: '/docs/getting-started'
}, {
  label: 'Components',
  icon: 'i-lucide-box',
  to: '/docs/components'
}, {
  label: 'Showcase',
  icon: 'i-lucide-presentation',
  to: '/showcase'
}]
</script>

<template>
  <UApp>
    <ClientOnly>
      <LazyUContentSearch
        :links="links"
      />
    </ClientOnly>
  </UApp>
</template>

컬러 모드 (Color Mode)

기본적으로 라이트·다크 모드 사이를 전환할 수 있는 명령 그룹이 커맨드 팔레트에 추가돼요. 이는 definePageMeta를 통해 특정 페이지에서 colorMode가 강제되지 않은 경우에만 적용돼요:

<script setup lang="ts">
definePageMeta({
  colorMode: 'dark'
})
</script>

color-mode prop을 false로 설정하면 이 동작을 비활성화할 수 있어요:

<template>
  <UApp>
    <ClientOnly>
      <LazyUContentSearch
        :color-mode="false"
      />
    </ClientOnly>
  </UApp>
</template>

API

Props

/**
 * Props for the ContentSearch component
 */
interface ContentSearchProps {
  /**
   * @default 'md'
   */
  size?: "sm" | "md" | "xs" | "lg" | "xl" | undefined;
  /**
   * Display a close button in the input (useful when inside a Modal for example).
   * `{ size: 'md', color: 'neutral', variant: 'ghost' }`{lang="ts-type"}
   * @default true
   */
  close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * Configure the input or hide it with `false`.
   * `{ fixed: true }`{lang="ts-type"}
   * @default true
   */
  input?: boolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue"> | undefined;
  /**
   * Keyboard shortcut to open the search (used by [`defineShortcuts`](https://ui.nuxt.com/docs/composables/define-shortcuts))
   * @default 'meta_k'
   */
  shortcut?: string | undefined;
  /**
   * Links group displayed as the first group in the command palette.
   */
  links?: T[] | undefined;
  navigation?: ContentNavigationItem[] | undefined;
  files?: ContentSearchFile[] | undefined;
  /**
   * Options for [useFuse](https://vueuse.org/integrations/useFuse) passed to the [CommandPalette](https://ui.nuxt.com/docs/components/command-palette).
   * @default {
fuseOptions: {
ignoreLocation: true,
includeMatches: true,
useTokenSearch: true,
threshold: 0.1,
keys: ['label', 'description', 'suffix']
},
resultLimit: 12,
matchAllWhenSearchEmpty: true
}
   */
  fuse?: UseFuseOptions<T> | undefined;
  /**
   * Async search function (e.g. from [`useSearchCollection`](https://content.nuxt.com/docs/utils/use-search-collection)).
   * When provided, ContentSearch calls it on each keystroke and uses the results instead of Fuse.
   * Results are mapped, sanitized, and grouped by navigation internally.
   */
  search?: (query: string, opts?: ContentSearchOptions | undefined): Promise<ContentSearchResult[]> | undefined;
  /**
   * Status of the async search index (e.g. from `useSearchCollection`).
   * When the status transitions to `'ready'`, the search is automatically re-triggered if there's a pending term.
   */
  searchStatus?: "error" | "loading" | "idle" | "ready" | undefined;
  /**
   * Delay (in milliseconds) before the search is triggered (debounced).
   * Keeps the input responsive by only running the search after typing settles.
   * Set to `0` to disable.
   * @default 100
   */
  searchDelay?: number | undefined;
  /**
   * When `true`, the theme command will be added to the groups.
   * @default true
   */
  colorMode?: boolean | undefined;
  ui?: { modal?: SlotClass; input?: SlotClass; } & { root?: SlotClass; input?: SlotClass; close?: SlotClass; back?: SlotClass; content?: SlotClass; footer?: SlotClass; viewport?: SlotClass; group?: SlotClass; empty?: SlotClass; label?: SlotClass; item?: SlotClass; itemLeadingIcon?: SlotClass; itemLeadingAvatar?: SlotClass; itemLeadingAvatarSize?: SlotClass; itemLeadingChip?: SlotClass; itemLeadingChipSize?: SlotClass; itemTrailing?: SlotClass; itemTrailingIcon?: SlotClass; itemTrailingHighlightedIcon?: SlotClass; itemTrailingKbds?: SlotClass; itemTrailingKbdsSize?: SlotClass; itemWrapper?: SlotClass; itemLabel?: SlotClass; itemLabelBase?: SlotClass; itemLabelPrefix?: SlotClass; itemLabelSuffix?: SlotClass; itemDescription?: SlotClass; } | undefined;
  title?: string | undefined;
  description?: string | undefined;
  /**
   * Render an overlay behind the modal.
   * @default true
   */
  overlay?: boolean | undefined;
  /**
   * Animate the modal when opening or closing.
   * @default true
   */
  transition?: boolean | undefined;
  /**
   * The content of the modal.
   */
  content?: Omit<DialogContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<DialogContentImplEmits>> | undefined;
  /**
   * When `false`, the modal will not close when clicking outside or pressing escape.
   * @default true
   */
  dismissible?: boolean | undefined;
  /**
   * When `true`, the modal will take up the full screen.
   * @default false
   */
  fullscreen?: boolean | undefined;
  /**
   * The modality of the dialog When set to `true`, <br>
   * interaction with outside elements will be disabled and only dialog content will be visible to screen readers.
   */
  modal?: boolean | undefined;
  /**
   * Render the modal in a portal.
   * @default true
   */
  portal?: string | false | true | HTMLElement | undefined;
  /**
   * When set to `false`, the dialog content will not be unmounted when closed, but instead hidden with CSS. <br>
   * Useful for SEO or when you want to improve performance by not remounting the component on every open.
   * @default true
   */
  unmountOnHide?: boolean | undefined;
  /**
   * The icon displayed in the input. Set to `false` to hide the icon.
   * @default appConfig.ui.icons.search
   */
  icon?: any;
  /**
   * The icon displayed on the right side of the input.
   * @default appConfig.ui.icons.search
   */
  trailingIcon?: any;
  /**
   * The icon displayed when an item is selected.
   * @default appConfig.ui.icons.check
   */
  selectedIcon?: any;
  /**
   * The icon displayed when an item has children.
   * @default appConfig.ui.icons.chevronRight
   */
  childrenIcon?: any;
  /**
   * The placeholder text for the input.
   * @default t('commandPalette.placeholder')
   */
  placeholder?: string | undefined;
  /**
   * Automatically focus the input when component is mounted.
   * @default true
   */
  autofocus?: boolean | undefined;
  /**
   * When `true`, the loading icon will be displayed.
   */
  loading?: boolean | undefined;
  /**
   * The icon when the `loading` prop is `true`.
   * @default appConfig.ui.icons.loading
   */
  loadingIcon?: any;
  /**
   * The icon displayed in the close button.
   * @default appConfig.ui.icons.close
   */
  closeIcon?: any;
  /**
   * Display a button to navigate back in history.
   * `{ size: 'md', color: 'neutral', variant: 'link' }`{lang="ts-type"}
   * @default true
   */
  back?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the back button.
   * @default appConfig.ui.icons.arrowLeft
   */
  backIcon?: any;
  /**
   * When `true`, prevents the user from interacting with listbox
   */
  disabled?: boolean | undefined;
  /**
   * When `true`, hover over item will trigger highlight
   */
  highlightOnHover?: boolean | undefined;
  /**
   * The key used to get the label from the item.
   * @default 'label'
   */
  labelKey?: string | undefined;
  /**
   * The key used to get the description from the item.
   * @default 'description'
   */
  descriptionKey?: string | undefined;
  /**
   * Whether to preserve the order of groups as defined in the `groups` prop when filtering.
   * When `false`, groups will appear based on item matches.
   * @default false
   */
  preserveGroupOrder?: boolean | undefined;
  /**
   * Enable virtualization for large lists.
   * Note: when enabled, all groups are flattened into a single list due to a limitation of Reka UI (https://github.com/unovue/reka-ui/issues/1885).
   * @default false
   */
  virtualize?: boolean | { overscan?: number | undefined; estimateSize?: number | ((index: number) => number) | undefined; } | undefined;
  groups?: CommandPaletteGroup<ContentSearchItem>[] | undefined;
  /**
   * @default ''
   */
  searchTerm?: string | undefined;
}

Slots

/**
 * Slots for the ContentSearch component
 */
interface ContentSearchSlots {
  empty(): any;
  footer(): any;
  back(): any;
  close(): any;
  item(): any;
  item-leading(): any;
  item-label(): any;
  item-description(): any;
  item-trailing(): any;
  group-label(): any;
  content(): any;
}

Emits

/**
 * Emitted events for the ContentSearch component
 */
interface ContentSearchEmits {
  update:searchTerm: (payload: [value: string]) => void;
}

노출 (Expose)

템플릿 ref를 통해 컴포넌트에 접근할 때 다음을 사용할 수 있어요:

Name Type
commandPaletteRef Ref<InstanceType<typeof UCommandPalette> | null>

테마 (Theme)

export default defineAppConfig({
  ui: {
    contentSearch: {
      slots: {
        modal: '',
        input: ''
      },
      variants: {
        fullscreen: {
          false: {
            modal: 'sm:max-w-3xl h-full sm:h-[28rem]'
          }
        },
        size: {
          xs: {},
          sm: {},
          md: {},
          lg: {},
          xl: {}
        }
      },
      defaultVariants: {
        size: 'md'
      }
    }
  }
})

변경 로그 (Changelog)

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

더 알아보기 (Learn more)