컴포넌트 커스터마이즈
컴포넌트 커스터마이즈 (Customize components)
Tailwind Variants API를 사용해 Nuxt UI 컴포넌트를 커스터마이즈하는 방법을 설명하는 문서예요. 고급·유연·유지보수하기 쉬운 스타일링을 위해 슬롯·변형·복합 변형·기본 변형을 이해하고, 전역 설정·ui prop·class prop으로 테마를 덮어쓰는 방법을 배울 수 있어요.
출처: Nuxt UI
본문
Tailwind Variants API로 Nuxt UI 컴포넌트를 커스터마이즈하는 방법을 배워보세요. 고급스럽고 유연하며 유지보수하기 쉬운 스타일링이 가능해요.
Tailwind Variants
Nuxt UI 컴포넌트는 Tailwind Variants API로 스타일이 지정돼요. 이 API는 변형(variant)을 만들고 컴포넌트 스타일을 관리하는 강력한 방법을 제공해요.
Slots
컴포넌트는 여러 개의 slots를 가질 수 있는데, 각각은 컴포넌트 안의 서로 다른 HTML 요소나 섹션을 나타내요. 이 슬롯들을 통해 유연하게 콘텐츠를 넣고 스타일을 지정할 수 있어요.
여러 슬롯을 가진 Card 컴포넌트를 예로 들어볼게요.
export default {
slots: {
root: 'rounded-lg overflow-hidden',
header: 'p-4 sm:px-6',
title: 'text-highlighted font-semibold',
description: 'mt-1 text-muted text-sm',
body: 'p-4 sm:p-6',
footer: 'p-4 sm:px-6'
}
}
<template>
<Primitive :as="props.as" data-slot="root" :class="ui.root({ class: [props.ui?.root, props.class] })">
<div data-slot="header" :class="ui.header({ class: props.ui?.header })">
<slot name="header" />
</div>
<div data-slot="body" :class="ui.body({ class: props.ui?.body })">
<slot />
</div>
<div data-slot="footer" :class="ui.footer({ class: props.ui?.footer })">
<slot name="footer" />
</div>
</Primitive>
</template>
[!NOTE]
위 코드 조각은 축약된 것이에요. 실제 컴포넌트는 각 슬롯에
v-if가드가 붙어 있고, 테마는 슬롯 위에variant스타일을 정의해요.
일부 컴포넌트는 슬롯이 없고 단일 루트 요소로만 구성돼요. 이 경우 테마는 Container 컴포넌트처럼 base 슬롯만 정의해요.
export default {
base: 'w-full max-w-(--ui-container) mx-auto px-4 sm:px-6 lg:px-8'
}
<template>
<Primitive :as="props.as" :class="ui({ class: [props.ui?.base, props.class] })">
<slot />
</Primitive>
</template>
[!NOTE]
슬롯이 없는 컴포넌트도
uiprop이 있어요. 슬롯마다 하나의 키 대신 단일base키를 노출해요. Link와 Icon은 예외로uiprop이 없으므로classprop으로 스타일을 덮어써요.
Variants
컴포넌트는 variants를 지원하며, 컴포넌트 prop에 따라 서로 다른 slots의 스타일을 동적으로 조절해요.
예를 들어 Avatar 컴포넌트는 size 변형을 사용해 모양을 제어해요.
export default {
slots: {
root: 'inline-flex items-center justify-center shrink-0 select-none overflow-hidden rounded-full align-middle bg-elevated',
image: 'h-full w-full rounded-[inherit] object-cover'
},
variants: {
size: {
sm: {
root: 'size-7 text-sm'
},
md: {
root: 'size-8 text-base'
},
lg: {
root: 'size-9 text-lg'
}
}
},
defaultVariants: {
size: 'md'
}
}
이렇게 하면 size prop이 root 슬롯에 해당하는 스타일을 적용해요.
<template>
<UAvatar src="https://github.com/nuxt.png" size="lg" />
</template>
Default Variants
defaultVariants 속성은 prop이 전달되지 않았을 때 각 변형의 기본값을 설정해요.
예를 들어 Avatar 컴포넌트의 기본 크기는 md로 설정돼 있어요.
export default {
slots: {
root: 'inline-flex items-center justify-center shrink-0 select-none overflow-hidden rounded-full align-middle bg-elevated',
image: 'h-full w-full rounded-[inherit] object-cover'
},
variants: {
size: {
sm: {
root: 'size-7 text-sm'
},
md: {
root: 'size-8 text-base'
},
lg: {
root: 'size-9 text-lg'
}
}
},
defaultVariants: {
size: 'md'
}
}
Nuxt:
[!TIP] See: /docs/getting-started/installation/nuxt#themedefaultvariants
nuxt.config.ts의theme.defaultVariants옵션을 사용해md와primary를 사용하는 모든 컴포넌트의 기본size와color를 덮어쓸 수 있어요.
Vue:
[!TIP] See: /docs/getting-started/installation/vue#themedefaultvariants
vite.config.ts의theme.defaultVariants옵션을 사용해md와primary를 사용하는 모든 컴포넌트의 기본size와color를 덮어쓸 수 있어요.
Compound Variants
일부 컴포넌트는 여러 변형 조건이 동시에 충족될 때 클래스를 적용하기 위해 compoundVariants 속성을 사용해요.
예를 들어 Button 컴포넌트는 특정 color와 variant 조합에 대해 클래스를 적용하는 데 compoundVariants 속성을 사용해요.
import type { ModuleOptions } from '../module'
export default (options: Required<ModuleOptions>) => ({
slots: {
base: ['rounded-md font-medium inline-flex items-center disabled:cursor-not-allowed aria-disabled:cursor-not-allowed disabled:opacity-75 aria-disabled:opacity-75', options.theme.transitions && 'transition-colors']
},
variants: {
color: {
...Object.fromEntries((options.theme.colors || []).map((color: string) => [color, ''])),
neutral: ''
},
variant: {
solid: '',
outline: '',
soft: '',
subtle: '',
ghost: '',
link: ''
}
},
compoundVariants: [
...(options.theme.colors || []).map((color: string) => ({
color,
variant: 'outline',
class: `ring ring-inset ring-${color}/50 text-${color} hover:bg-${color}/10 active:bg-${color}/10 disabled:bg-transparent aria-disabled:bg-transparent dark:disabled:bg-transparent dark:aria-disabled:bg-transparent outline-${color}/25 focus-visible:outline-3 focus-visible:ring-${color}`
})),
{
color: 'neutral',
variant: 'outline',
class: 'ring ring-inset ring-accented text-default bg-default hover:bg-elevated active:bg-elevated disabled:bg-default aria-disabled:bg-default outline-inverted/25 focus-visible:outline-3 focus-visible:ring-inverted'
}
],
defaultVariants: {
color: 'primary',
variant: 'solid'
}
})
테마 커스터마이즈 (Customize theme)
Nuxt UI 컴포넌트의 모양을 커스터마이즈하는 방법은 여러 가지가 있어요. 모든 컴포넌트를 한 번에 하거나 컴포넌트별로 할 수 있어요.
[!NOTE]
Tailwind Variants는 내부적으로
tailwind-merge를 사용해 클래스를 병합하므로 충돌하는 클래스에 대해 걱정할 필요가 없어요.
[!TIP]
각 컴포넌트의 테마를 두 가지 방법으로 탐색할 수 있어요.
- 각 컴포넌트 문서의
Theme섹션을 확인하세요.- GitHub 저장소의
src/theme에서 소스 코드를 직접 살펴보세요.
전역 설정 (Global config)
Nuxt:
app.config.ts 안에서 테마 객체와 똑같은 구조를 사용해 컴포넌트 테마를 전역으로 덮어쓸 수 있어요.
Vue:
vite.config.ts 안에서 테마 객체와 똑같은 구조를 사용해 컴포넌트 테마를 전역으로 덮어쓸 수 있어요.
컴포넌트의 slots, variants, compoundVariants, defaultVariants를 커스터마이즈해 컴포넌트의 기본 테마를 바꿀 수 있어요.
Nuxt:
export default defineAppConfig({
ui: {
button: {
slots: {
base: 'font-bold'
},
variants: {
size: {
md: {
leadingIcon: 'size-4'
}
}
},
compoundVariants: [{
color: 'neutral',
variant: 'outline',
class: 'ring-default hover:bg-accented'
}],
defaultVariants: {
color: 'neutral',
variant: 'outline'
}
}
}
})
Vue:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ui from '@nuxt/ui/vite'
export default defineConfig({
plugins: [
vue(),
ui({
ui: {
button: {
slots: {
base: 'font-bold'
},
variants: {
size: {
md: {
leadingIcon: 'size-4'
}
}
},
compoundVariants: [{
color: 'neutral',
variant: 'outline',
class: 'ring-default hover:bg-accented'
}],
defaultVariants: {
color: 'neutral',
variant: 'outline'
}
}
}
})
]
})
[!NOTE]
이 예시에서
font-bold는 모든 버튼의font-medium을 덮어쓰고,size-4는size="md"일 때 leading 아이콘의size-5클래스를 덮어쓰며,ring-default hover:bg-accented는color="neutral"이고variant="outline"일 때ring-accented hover:bg-elevated를 덮어써요. 이제 버튼의 기본값은color="neutral"이고variant="outline"이 돼요.
기본적으로 이 클래스들은 컴포넌트의 기본값에 병합돼요. 슬롯을 함수로 설정하면 병합 대신 교체할 수도 있어요. 이 함수는 슬롯의 기본 클래스들을 인자로 받으므로 일부를 재사용할 수 있어요. variants와 compoundVariants의 클래스는 문자열을 전달할 때와 마찬가지로 여전히 최상단에 적용돼요.
Nuxt:
export default defineAppConfig({
ui: {
button: {
slots: {
label: () => 'text-base font-bold'
}
}
}
})
Vue:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ui from '@nuxt/ui/vite'
export default defineConfig({
plugins: [
vue(),
ui({
ui: {
button: {
slots: {
label: () => 'text-base font-bold'
}
}
}
})
]
})
Nuxt:
[!WARNING]
슬롯을 함수로 설정할 때는 한 곳에서만 설정하세요. Nuxt는
defuFn으로 모든 layer의app.config.ts를 병합하는데, 이는 키에 이미 있는 값으로 함수를 호출하고 그 결과만 유지해요. 그러면 Nuxt UI는 일반 문자열을 읽으므로 클래스들이 기본값 위에 병합되며 교체되지 않아요.
Nuxt:
[!TIP] See: /docs/getting-started/installation/nuxt#themeunstyled
모든 컴포넌트의 기본 클래스를 한 번에 제거하려면
nuxt.config.ts의theme.unstyled옵션을 사용하세요.
Vue:
[!TIP] See: /docs/getting-started/installation/vue#themeunstyled
모든 컴포넌트의 기본 클래스를 한 번에 제거하려면
vite.config.ts의theme.unstyled옵션을 사용하세요.
Theme 컴포넌트
Theme 컴포넌트는 앱의 나머지 부분에는 영향을 주지 않고 모든 하위 요소의 슬롯과 prop 기본값을 덮어써요. 이는 전역 설정보다 우선하지만 ui와 class prop은 여전히 이것보다 우선해요. 슬롯은 병합 대신 클래스를 교체하려면 동일한 함수 형태를 받을 수 있어요. 이는 ui prop과 같은 지점에서 해석되므로 동일하게 동작해요.
<template>
<UTheme
:ui="{
button: {
base: 'rounded-full'
}
}"
>
<div class="flex items-center gap-2">
<UButton label="Button" color="neutral" />
<UButton label="Button" color="neutral" variant="outline" />
<UButton label="Button" color="neutral" variant="subtle" />
</div>
</UTheme>
</template>
ui prop
ui prop을 사용해 컴포넌트의 slots을 덮어쓸 수도 있어요. 이는 전역 설정과 해석된 variants 모두보다 우선해요.
<template>
<UButton trailing-icon="i-lucide-chevron-right" size="md" color="neutral" variant="outline" :ui="{
trailingIcon: 'rotate-90 size-3'
}">
Button
</UButton>
</template>
[!NOTE]
이 예시에서는
md크기 변형이size-5클래스를 적용하더라도trailingIcon슬롯이size-3으로 덮어써져요.
슬롯 값은 함수일 수도 있는데, 이 경우 클래스를 병합하는 대신 교체해요.
<template>
<UButton :ui="{ label: () => 'text-base font-bold' }" label="Button" />
</template>
[!NOTE]
uiprop은variants이후에 해석되므로 전역 설정과 달리 여기서 함수는 슬롯의 해석된 클래스를 교체해요. 이 함수의 인자에는variants와compoundVariants가 매칭한 내용이 포함돼요. 같은 슬롯에 대한classprop은 여전히 반환된 클래스 위에 병합돼요.
class prop
class prop을 사용해 root 또는 base 슬롯의 클래스를 덮어쓸 수 있어요. 이는 전역 설정과 해석된 variants 모두보다 우선해요.
<template>
<UButton class="font-bold rounded-full">
Button
</UButton>
</template>
[!NOTE]
이 예시에서
font-bold클래스는 이 버튼의 기본font-medium클래스를 덮어써요.