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

Drawer

원문 보기 위키 갱신

화면 밖으로 부드럽게 밀려 들어오고 나가는 드로어 컴포넌트예요.

출처: Nuxt UI

본문

사용법

Drawer의 기본 슬롯에 Button이나 다른 어떤 컴포넌트든 넣어 주세요.

그다음 #content 슬롯에 Drawer가 열렸을 때 표시할 콘텐츠를 추가해 주세요.

<template>
  <UDrawer>
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="h-48 m-4" />
    </template></UDrawer>
</template>

#header, #body, #footer 슬롯을 사용해 Drawer의 콘텐츠를 커스터마이즈할 수도 있어요.

Title

title prop으로 Drawer 헤더의 제목을 설정할 수 있어요.

<template>
  <UDrawer title="Drawer with title">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #body>
      <Placeholder class="h-48" />
    </template></UDrawer>
</template>

Description

description prop으로 Drawer 헤더의 설명을 설정할 수 있어요.

<template>
  <UDrawer title="Drawer with description" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #body>
      <Placeholder class="h-48" />
    </template></UDrawer>
</template>

Close 4.10+

close prop으로 Drawer에 닫기 버튼을 표시할 수 있어요. 기본값은 false예요.

Button 컴포넌트의 어떤 속성이든 전달해 버튼을 커스터마이즈할 수 있어요.

<template>
  <UDrawer title="Drawer with close button" :close="{
  color: 'primary',
  variant: 'outline',
  class: 'rounded-full'
}">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #body>
      <Placeholder class="h-48" />
    </template></UDrawer>
</template>

Close Icon 4.10+

close-icon prop으로 닫기 버튼의 Icon을 커스터마이즈할 수 있어요. 기본값은 i-lucide-x예요.

<template>
  <UDrawer title="Drawer with close button" close close-icon="i-lucide-arrow-right">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #body>
      <Placeholder class="h-48" />
    </template></UDrawer>
</template>

Direction

direction prop으로 Drawer의 방향을 제어할 수 있어요. 기본값은 bottom이에요.

<template>
  <UDrawer direction="right">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="min-w-96 min-h-96 size-full m-4" />
    </template></UDrawer>
</template>

Inset

inset prop으로 Drawer를 가장자리에서 안쪽으로 들여쓸 수 있어요.

<template>
  <UDrawer direction="right" inset>
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="min-w-96 min-h-96 size-full m-4" />
    </template></UDrawer>
</template>

Handle

handle prop으로 Drawer에 핸들(handle)이 있는지 제어할 수 있어요. 기본값은 true예요.

<template>
  <UDrawer :handle="false">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="h-48 m-4" />
    </template></UDrawer>
</template>

Handle Only

handle-only prop으로 Drawer를 핸들로만 드래그할 수 있게 할 수 있어요.

<template>
  <UDrawer handle-only>
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="h-48 m-4" />
    </template></UDrawer>
</template>

Overlay

overlay prop으로 Drawer에 오버레이가 있는지 제어할 수 있어요. 기본값은 true예요.

<template>
  <UDrawer :overlay="false">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="h-48 m-4" />
    </template></UDrawer>
</template>

modal prop으로 Drawer가 외부 콘텐츠와의 상호작용을 막을지 제어할 수 있어요. 기본값은 true예요.

[!NOTE]

modal을 false로 설정하면 오버레이가 자동으로 비활성화되고 외부 콘텐츠와 상호작용할 수 있게 돼요.

<template>
  <UDrawer :modal="false">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="h-48 m-4" />
    </template></UDrawer>
</template>

Dismissible

dismissible prop으로 Drawer를 외부를 클릭하거나 esc 키를 눌렀을 때 닫을 수 있게 할지 제어할 수 있어요. 기본값은 true예요.

[!NOTE]

사용자가 닫으려고 하면 close:prevent 이벤트가 발생해요.

[!TIP]

modal: false와 dismissible: false를 함께 사용하면 Drawer를 닫지 않고도 배경과 상호작용할 수 있어요.

<script setup lang="ts">
const open = ref(false)
</script>

<template>
  <UDrawer
    v-model:open="open"
    title="Drawer non-dismissible"
    close
    :dismissible="false"
    :modal="false"
    :handle="false"
  >
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />

    <template #body>
      <Placeholder class="size-full min-h-48" />
    </template>
  </UDrawer>
</template>

Scale Background

should-scale-background prop으로 Drawer가 열렸을 때 배경을 확대해 시각적인 깊이감을 만들 수 있어요. set-background-color-on-scale prop을 false로 설정하면 배경 색상이 바뀌지 않게 할 수 있어요.

<template>
  <UDrawer should-scale-background set-background-color-on-scale>
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />
  
    <template #content>
      <Placeholder class="h-48 m-4" />
    </template></UDrawer>
</template>

[!WARNING]

이 기능이 동작하도록 앱의 부모 요소에 data-vaul-drawer-wrapper 디렉티브를 추가해 주세요.

<template>
  <UApp>
    <div class="bg-default" data-vaul-drawer-wrapper>
      <NuxtLayout>
        <NuxtPage />
      </NuxtLayout>
    </div>
  </UApp>
</template>
export default defineNuxtConfig({
  app: {
    rootAttrs: {
      'data-vaul-drawer-wrapper': '',
      'class': 'bg-default'
    }
  }
})

예시

열림 상태 제어하기

default-open prop이나 v-model:open 디렉티브를 사용해 열림 상태를 제어할 수 있어요.

<script setup lang="ts">
const open = ref(false)

defineShortcuts({
  o: () => open.value = !open.value
})
</script>

<template>
  <UDrawer v-model:open="open">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </UDrawer>
</template>

[!NOTE]

이 예시에서는 defineShortcuts를 활용해 O 키를 눌러 Drawer를 열고 닫을 수 있어요.

[!TIP]

이렇게 하면 트리거를 Drawer 밖으로 옮기거나 완전히 제거할 수도 있어요.

반응형 드로어

예를 들어 데스크톱에서는 Modal 컴포넌트를, 모바일에서는 Drawer를 렌더링할 수 있어요.

<script lang="ts" setup>
import { createReusableTemplate, useMediaQuery } from '@vueuse/core'

const [DefineFormTemplate, ReuseFormTemplate] = createReusableTemplate()
const isDesktop = useMediaQuery('(min-width: 768px)')

const open = ref(false)

const state = reactive({
  email: undefined
})

const title = 'Edit profile'
const description = 'Make changes to your profile here. Click save when you\'re done.'
</script>

<template>
  <DefineFormTemplate>
    <UForm :state="state" class="space-y-4">
      <UFormField label="Email" name="email" required>
        <UInput v-model="state.email" placeholder="you@example.com" required />
      </UFormField>

      <UButton label="Save changes" type="submit" />
    </UForm>
  </DefineFormTemplate>

  <UModal v-if="isDesktop" v-model:open="open" :title="title" :description="description">
    <UButton label="Edit profile" color="neutral" variant="outline" />

    <template #body>
      <ReuseFormTemplate />
    </template>
  </UModal>

  <UDrawer v-else v-model:open="open" :title="title" :description="description">
    <UButton label="Edit profile" color="neutral" variant="outline" />

    <template #body>
      <ReuseFormTemplate />
    </template>
  </UDrawer>
</template>

중첩 드로어

nested prop을 사용해 드로어를 서로 중첩할 수 있어요.

<template>
  <UDrawer :ui="{ content: 'h-full', overlay: 'bg-inverted/30' }">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />

    <template #footer>
      <UDrawer nested :ui="{ content: 'h-full', overlay: 'bg-inverted/30' }">
        <UButton color="neutral" variant="outline" label="Open nested" />

        <template #content>
          <Placeholder class="flex-1 m-4" />
        </template>
      </UDrawer>
    </template>
  </UDrawer>
</template>

푸터 슬롯과 함께 사용하기

#footer 슬롯을 사용해 Drawer의 본문 뒤에 콘텐츠를 추가할 수 있어요.

<script setup lang="ts">
const open = ref(false)
</script>

<template>
  <UDrawer v-model:open="open" title="Drawer with footer" description="This is useful when you want a form in a Drawer." :ui="{ container: 'max-w-xl mx-auto' }">
    <UButton label="Open" color="neutral" variant="subtle" trailing-icon="i-lucide-chevron-up" />

    <template #body>
      <Placeholder class="h-48" />
    </template>

    <template #footer>
      <UButton label="Submit" color="neutral" class="justify-center" />
      <UButton label="Cancel" color="neutral" variant="outline" class="justify-center" @click="open = false" />
    </template>
  </UDrawer>
</template>

커맨드 팔레트와 함께 사용하기

Drawer의 콘텐츠 안에 CommandPalette 컴포넌트를 사용할 수 있어요.

<script setup lang="ts">
const searchTerm = ref('')

const { data: users, status, execute } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'drawer-command-palette-users',
  params: { q: searchTerm },
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  immediate: false
})

const groups = computed(() => [{
  id: 'users',
  label: searchTerm.value ? `Users matching “${searchTerm.value}”...` : 'Users',
  items: users.value || [],
  ignoreFilter: true
}])

function onOpen() {
  if (!users.value?.length) {
    execute()
  }
}
</script>

<template>
  <UDrawer :handle="false" @update:open="onOpen">
    <UButton
      label="Search users..."
      color="neutral"
      variant="subtle"
      icon="i-lucide-search"
    />

    <template #content>
      <UCommandPalette
        v-model:search-term="searchTerm"
        :loading="status === 'pending'"
        :groups="groups"
        placeholder="Search users..."
        class="h-80"
      />
    </template>
  </UDrawer>
</template>

[!NOTE]

이 예시는 immediate: false와 함께 useLazyFetch를 사용해 Drawer가 열릴 때만 데이터를 가져와요.

API

Props

/**
 * Props for the Drawer component
 */
interface DrawerProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  title?: string | undefined;
  description?: string | undefined;
  /**
   * Whether to inset the drawer from the edges.
   * @default false
   */
  inset?: boolean | undefined;
  /**
   * The content of the drawer.
   */
  content?: Omit<DialogContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<DialogContentImplEmits>> | undefined;
  /**
   * Render an overlay behind the drawer.
   * @default true
   */
  overlay?: boolean | undefined;
  /**
   * Render a handle on the drawer.
   * @default true
   */
  handle?: boolean | undefined;
  /**
   * Render the drawer in a portal.
   * @default true
   */
  portal?: string | false | true | HTMLElement | undefined;
  /**
   * Whether the drawer is nested in another drawer.
   * @default false
   */
  nested?: boolean | undefined;
  /**
   * Display a close button to dismiss the drawer.
   * `{ size: 'md', color: 'neutral', variant: 'ghost' }`{lang="ts-type"}
   * @default false
   */
  close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the close button.
   * @default appConfig.ui.icons.close
   */
  closeIcon?: any;
  ui?: { overlay?: SlotClass; content?: SlotClass; handle?: SlotClass; container?: SlotClass; header?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; actions?: SlotClass; body?: SlotClass; footer?: SlotClass; close?: SlotClass; } | undefined;
  activeSnapPoint?: null | string | number | undefined;
  /**
   * Number between 0 and 1 that determines when the drawer should be closed.
   * Example: threshold of 0.5 would close the drawer if the user swiped for 50% of the height of the drawer or more.
   */
  closeThreshold?: number | undefined;
  shouldScaleBackground?: boolean | undefined;
  /**
   * When `false` we don't change body's background color when the drawer is open.
   */
  setBackgroundColorOnScale?: boolean | undefined;
  /**
   * Duration for which the drawer is not draggable after scrolling content inside of the drawer.
   */
  scrollLockTimeout?: number | undefined;
  /**
   * When `true`, don't move the drawer upwards if there's space, but rather only change it's height so it's fully scrollable when the keyboard is open
   */
  fixed?: boolean | undefined;
  /**
   * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
   * Use this in combination with the `open` prop, otherwise you won't be able to open/close the drawer.
   * @default true
   */
  dismissible?: boolean | undefined;
  /**
   * When `false` it allows to interact with elements outside of the drawer without closing it.
   * @default true
   */
  modal?: boolean | undefined;
  open?: boolean | undefined;
  /**
   * Opened by default, skips initial enter animation. Still reacts to `open` state changes
   */
  defaultOpen?: boolean | undefined;
  /**
   * Direction of the drawer. Can be `top` or `bottom`, `left`, `right`.
   * @default 'bottom'
   */
  direction?: "bottom" | "top" | "right" | "left" | undefined;
  /**
   * When `true` the `body` doesn't get any styles assigned from Vaul
   */
  noBodyStyles?: boolean | undefined;
  /**
   * When `true` only allows the drawer to be dragged by the `<Drawer.Handle />` component.
   */
  handleOnly?: boolean | undefined;
  preventScrollRestoration?: boolean | undefined;
  /**
   * Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up.
   * Should go from least visible. Example `[0.2, 0.5, 0.8]`.
   * You can also use px values, which doesn't take screen height into account.
   */
  snapPoints?: (string | number)[] | undefined;
}

Slots

/**
 * Slots for the Drawer component
 */
interface DrawerSlots {
  default(): any;
  content(): any;
  header(): any;
  title(): any;
  description(): any;
  actions(): any;
  close(): any;
  body(): any;
  footer(): any;
}

Emits

/**
 * Emitted events for the Drawer component
 */
interface DrawerEmits {
  close: (payload: []) => void;
  drag: (payload: [percentageDragged: number]) => void;
  after:leave: (payload: []) => void;
  after:enter: (payload: []) => void;
  close:prevent: (payload: []) => void;
  release: (payload: [open: boolean]) => void;
  update:open: (payload: [open: boolean]) => void;
  update:activeSnapPoint: (payload: [val: string | number]) => void;
  animationEnd: (payload: [open: boolean]) => void;
}

테마

export default defineAppConfig({
  ui: {
    drawer: {
      slots: {
        overlay: 'fixed inset-0 bg-elevated/75',
        content: 'fixed bg-default ring ring-default flex focus:outline-none',
        handle: [
          'shrink-0 !bg-accented',
          'transition-opacity ease-out'
        ],
        container: 'w-full flex flex-col gap-4 p-4 overflow-y-auto',
        header: 'flex items-center gap-1.5 min-h-8',
        wrapper: 'min-w-0 flex-1',
        title: 'text-highlighted font-semibold',
        description: 'mt-1 text-muted text-sm',
        actions: 'flex items-center gap-1.5 shrink-0 ms-auto',
        body: 'flex-1',
        footer: 'flex flex-col gap-1.5',
        close: ''
      },
      variants: {
        direction: {
          top: {
            content: 'mb-24 flex-col-reverse',
            handle: 'mb-4'
          },
          right: {
            content: 'flex-row rtl:flex-row-reverse',
            handle: '!ml-4'
          },
          bottom: {
            content: 'mt-24 flex-col',
            handle: 'mt-4'
          },
          left: {
            content: 'flex-row-reverse rtl:flex-row',
            handle: '!mr-4'
          }
        },
        inset: {
          true: {
            content: 'rounded-lg after:hidden overflow-hidden [--initial-transform:calc(100%+1.5rem)]'
          }
        },
        snapPoints: {
          true: ''
        }
      },
      compoundVariants: [
        {
          direction: [
            'top',
            'bottom'
          ],
          class: {
            content: 'h-auto max-h-[96%]',
            handle: '!w-12 !h-1.5 mx-auto'
          }
        },
        {
          direction: [
            'top',
            'bottom'
          ],
          snapPoints: true,
          class: {
            content: 'h-full'
          }
        },
        {
          direction: [
            'right',
            'left'
          ],
          class: {
            content: 'w-auto max-w-[calc(100%-2rem)]',
            handle: '!h-12 !w-1.5 mt-auto mb-auto'
          }
        },
        {
          direction: [
            'right',
            'left'
          ],
          snapPoints: true,
          class: {
            content: 'w-full'
          }
        },
        {
          direction: 'top',
          inset: true,
          class: {
            content: 'inset-x-4 top-4'
          }
        },
        {
          direction: 'top',
          inset: false,
          class: {
            content: 'inset-x-0 top-0 rounded-b-lg'
          }
        },
        {
          direction: 'bottom',
          inset: true,
          class: {
            content: 'inset-x-4 bottom-4'
          }
        },
        {
          direction: 'bottom',
          inset: false,
          class: {
            content: 'inset-x-0 bottom-0 rounded-t-lg'
          }
        },
        {
          direction: 'left',
          inset: true,
          class: {
            content: 'inset-y-4 left-4'
          }
        },
        {
          direction: 'left',
          inset: false,
          class: {
            content: 'inset-y-0 left-0 rounded-r-lg'
          }
        },
        {
          direction: 'right',
          inset: true,
          class: {
            content: 'inset-y-4 right-4'
          }
        },
        {
          direction: 'right',
          inset: false,
          class: {
            content: 'inset-y-0 right-0 rounded-l-lg'
          }
        }
      ]
    }
  }
})

변경 기록

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


사이트맵

전체 페이지 목록은 사이트맵에서 확인할 수 있어요.

더 알아보기 (Learn more)