AuthForm
로그인, 회원가입, 비밀번호 재설정 폼을 만들 수 있는 커스터마이징 가능한 Form 컴포넌트예요. Form 컴포넌트 위에 만들어져 있어서 폼 검증과 상태 관리를 기본으로 갖추고 있어요.
출처: Nuxt UI
본문
로그인, 회원가입, 비밀번호 재설정 폼을 만들 수 있는 커스터마이징 가능한 Form 컴포넌트예요.
사용법
Form 컴포넌트 위에 만들어져 있어서, AuthForm 컴포넌트를 페이지에서 바로 쓰거나 PageCard로 감싸서 사용할 수 있어요.
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent, AuthFormField } from '@nuxt/ui'
const toast = useToast()
const fields: AuthFormField[] = [{
name: 'email',
type: 'email',
label: 'Email',
placeholder: 'Enter your email',
required: true
}, {
name: 'password',
label: 'Password',
type: 'password',
placeholder: 'Enter your password',
required: true
}, {
name: 'remember',
label: 'Remember me',
type: 'checkbox'
}]
const providers = [{
label: 'Google',
icon: 'i-simple-icons-google',
onClick: () => {
toast.add({ title: 'Google', description: 'Login with Google' })
}
}, {
label: 'GitHub',
icon: 'i-simple-icons-github',
onClick: () => {
toast.add({ title: 'GitHub', description: 'Login with GitHub' })
}
}]
const schema = z.object({
email: z.email('Invalid email'),
password: z.string('Password is required').min(8, 'Must be at least 8 characters')
})
type Schema = z.output<typeof schema>
function onSubmit(payload: FormSubmitEvent<Schema>) {
console.log('Submitted', payload)
}
</script>
<template>
<div class="flex flex-col items-center justify-center gap-4 p-4">
<UPageCard class="w-full max-w-md">
<UAuthForm
:schema="schema"
title="Login"
description="Enter your credentials to access your account."
icon="i-lucide-user"
:fields="fields"
:providers="providers"
@submit="onSubmit"
/>
</UPageCard>
</div>
</template>
필드 (Fields)
폼은 fields prop을 기반으로 스스로 구성되고, 상태는 내부적으로 처리돼요.
fields prop은 다음 속성을 가진 객체 배열로 사용하면 돼요:
name: stringtype: 'checkbox' | 'select' | 'otp' | 'InputHTMLAttributes['type']'
각 필드는 반드시 type 속성을 포함해야 해요. 이 속성이 입력 컴포넌트와 적용될 추가 prop들을 결정하거든요. checkbox 필드는 Checkbox의 props를, select 필드는 SelectMenu의 props를, otp 필드는 PinInput의 props를, 나머지 타입은 Input의 props를 사용해요.
또한 FormField 컴포넌트의 어떤 속성이든 각 필드에 전달할 수 있어요.
<script setup lang="ts">
import type { AuthFormField } from '@nuxt/ui'
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "email",
label: "Email",
placeholder: "Enter your email",
required: true
},
{
name: "password",
type: "password",
label: "Password",
placeholder: "Enter your password",
required: true
},
{
name: "country",
type: "select",
label: "Country",
placeholder: "Select country",
items: [
{
label: "United States",
value: "us"
},
{
label: "France",
value: "fr"
},
{
label: "United Kingdom",
value: "uk"
},
{
label: "Australia",
value: "au"
}
]
},
{
name: "otp",
type: "otp",
label: "OTP",
length: 6,
placeholder: "○"
},
{
name: "remember",
type: "checkbox",
label: "Remember me",
description: "You will be logged in for 30 days."
}
])
</script>
<template>
<UAuthForm :fields="fields" class="max-w-sm" />
</template>
타이틀 (Title)
title prop으로 Form의 제목을 설정할 수 있어요.
<script setup lang="ts">
import type { AuthFormField } from '@nuxt/ui'
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" :fields="fields" class="max-w-md" />
</template>
설명 (Description)
description prop으로 Form의 설명을 설정할 수 있어요.
<script setup lang="ts">
import type { AuthFormField } from '@nuxt/ui'
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" description="Enter your credentials to access your account." :fields="fields" class="max-w-md" />
</template>
아이콘 (Icon)
icon prop으로 Form의 아이콘을 설정할 수 있어요.
<script setup lang="ts">
import type { AuthFormField } from '@nuxt/ui'
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" description="Enter your credentials to access your account." icon="i-lucide-user" :fields="fields" class="max-w-md" />
</template>
프로바이더 (Providers)
providers prop으로 폼에 프로바이더를 추가할 수 있어요.
Button 컴포넌트의 어떤 속성이든 전달할 수 있는데요, variant, color, to 같은 것들이에요.
<script setup lang="ts">
import type { ButtonProps, AuthFormField } from '@nuxt/ui'
const providers = ref<ButtonProps[]>([
{
label: "Google",
icon: "i-simple-icons-google",
color: "neutral",
variant: "subtle"
},
{
label: "GitHub",
icon: "i-simple-icons-github",
color: "neutral",
variant: "subtle"
}
])
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" description="Enter your credentials to access your account." icon="i-lucide-user" :providers="providers" :fields="fields" class="max-w-md" />
</template>
구분선 (Separator)
separator prop으로 프로바이더와 필드 사이의 Separator를 커스터마이징할 수 있어요. 기본값은 or이에요.
<script setup lang="ts">
import type { ButtonProps, AuthFormField } from '@nuxt/ui'
const providers = ref<ButtonProps[]>([
{
label: "Google",
icon: "i-simple-icons-google",
color: "neutral",
variant: "subtle"
},
{
label: "GitHub",
icon: "i-simple-icons-github",
color: "neutral",
variant: "subtle"
}
])
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" description="Enter your credentials to access your account." icon="i-lucide-user" :providers="providers" :fields="fields" separator="Providers" class="max-w-md" />
</template>
Separator 컴포넌트의 어떤 속성이든 전달해서 커스터마이징할 수도 있어요.
<script setup lang="ts">
import type { ButtonProps, AuthFormField } from '@nuxt/ui'
const providers = ref<ButtonProps[]>([
{
label: "Google",
icon: "i-simple-icons-google",
color: "neutral",
variant: "subtle"
},
{
label: "GitHub",
icon: "i-simple-icons-github",
color: "neutral",
variant: "subtle"
}
])
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" description="Enter your credentials to access your account." icon="i-lucide-user" :providers="providers" :fields="fields" :separator="{
icon: 'i-lucide-user'
}" class="max-w-md" />
</template>
제출 버튼 (Submit)
submit prop으로 Form의 제출 버튼을 바꿀 수 있어요.
Button 컴포넌트의 어떤 속성이든 전달할 수 있는데요, variant, color, to 같은 것들이에요.
<script setup lang="ts">
import type { AuthFormField } from '@nuxt/ui'
const fields = ref<AuthFormField[]>([
{
name: "email",
type: "text",
label: "Email"
},
{
name: "password",
type: "password",
label: "Password"
}
])
</script>
<template>
<UAuthForm title="Login" description="Enter your credentials to access your account." icon="i-lucide-user" :fields="fields" :submit="{
label: 'Submit',
color: 'error',
variant: 'subtle'
}" class="max-w-md" />
</template>
예시 (Examples)
페이지 안에서 (Within a page)
AuthForm 컴포넌트를 PageCard 컴포넌트로 감싸면, 예를 들어 login.vue 페이지에서 멋지게 표시할 수 있어요.
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent, AuthFormField } from '@nuxt/ui'
const toast = useToast()
const fields: AuthFormField[] = [{
name: 'email',
type: 'email',
label: 'Email',
placeholder: 'Enter your email',
required: true
}, {
name: 'password',
label: 'Password',
type: 'password',
placeholder: 'Enter your password',
required: true
}, {
name: 'remember',
label: 'Remember me',
type: 'checkbox'
}]
const providers = [{
label: 'Google',
icon: 'i-simple-icons-google',
onClick: () => {
toast.add({ title: 'Google', description: 'Login with Google' })
}
}, {
label: 'GitHub',
icon: 'i-simple-icons-github',
onClick: () => {
toast.add({ title: 'GitHub', description: 'Login with GitHub' })
}
}]
const schema = z.object({
email: z.email('Invalid email'),
password: z.string('Password is required').min(8, 'Must be at least 8 characters')
})
type Schema = z.output<typeof schema>
function onSubmit(payload: FormSubmitEvent<Schema>) {
console.log('Submitted', payload)
}
</script>
<template>
<div class="flex flex-col items-center justify-center gap-4 p-4">
<UPageCard class="w-full max-w-md">
<UAuthForm
:schema="schema"
:fields="fields"
:providers="providers"
title="Welcome back!"
icon="i-lucide-lock"
@submit="onSubmit"
>
<template #description>
Don't have an account? <ULink to="#" class="text-primary font-medium">Sign up</ULink>.
</template>
<template #password-hint>
<ULink to="#" class="text-primary font-medium" tabindex="-1">Forgot password?</ULink>
</template>
<template #validation>
<UAlert color="error" icon="i-lucide-info" title="Error signing in" />
</template>
<template #footer>
By signing in, you agree to our <ULink to="#" class="text-primary font-medium">Terms of Service</ULink>.
</template>
</UAuthForm>
</UPageCard>
</div>
</template>
API
Props
/**
* Props for the AuthForm component
*/
interface AuthFormProps {
/**
* The element or component this component should render as.
* @default 'div'
*/
as?: any;
/**
* The icon displayed above the title.
*/
icon?: any;
title?: string | undefined;
description?: string | undefined;
fields?: F[] | undefined;
/**
* Display a list of Button under the description.
* `{ color: 'neutral', variant: 'subtle', block: true }`{lang="ts-type"}
*/
providers?: ButtonProps[] | undefined;
/**
* The text displayed in the separator.
* @default 'or'
*/
separator?: string | SeparatorProps | undefined;
/**
* Display a submit button at the bottom of the form.
* `{ label: 'Continue', block: true }`{lang="ts-type"}
*/
submit?: Omit<ButtonProps, LinkPropsKeys> | undefined;
schema?: T | undefined;
validate?: (state: Partial<InferInput<T>>): FormError<string>[] | Promise<FormError<string>[]> | undefined;
validateOn?: FormInputEvents[] | undefined;
validateOnInputDelay?: number | undefined;
disabled?: boolean | undefined;
loading?: boolean | undefined;
loadingAuto?: boolean | undefined;
ui?: { root?: SlotClass; header?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; title?: SlotClass; description?: SlotClass; body?: SlotClass; providers?: SlotClass; checkbox?: SlotClass; select?: SlotClass; password?: SlotClass; otp?: SlotClass; input?: SlotClass; separator?: SlotClass; form?: SlotClass; footer?: SlotClass; } | undefined;
name?: string | undefined;
autocomplete?: string | undefined;
acceptcharset?: string | undefined;
action?: string | undefined;
enctype?: string | undefined;
method?: string | undefined;
novalidate?: false | true | "true" | "false" | undefined;
target?: string | undefined;
}
[!NOTE] See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attributes
This component also supports all native
<form>HTML attributes.
Slots
/**
* Slots for the AuthForm component
*/
interface AuthFormSlots {
header(): any;
leading(): any;
title(): any;
description(): any;
providers(): any;
separator(): any;
validation(): any;
submit(): any;
footer(): any;
}
Emits
/**
* Emitted events for the AuthForm component
*/
interface AuthFormEmits {
submit: (payload: [payload: FormSubmitEvent<InferOutput<T>>]) => void;
}
Expose
타입이 지정된 컴포넌트 인스턴스(formRef와 state를 노출)에 useTemplateRef로 접근할 수 있어요. 예를 들어 별도의 폼(가령 "reset" 폼)에서는 이렇게 쓸 수 있어요:
<script setup lang="ts">
const authForm = useTemplateRef('authForm')
</script>
<template>
<UAuthForm ref="authForm" />
</template>
이렇게 하면 다음(노출된) 속성들에 접근할 수 있어요:
| Name | Type |
|---|---|
formRef |
Ref<HTMLFormElement | null> |
state |
Reactive<FormStateType> |
테마 (Theme)
export default defineAppConfig({
ui: {
authForm: {
slots: {
root: 'w-full space-y-6',
header: 'flex flex-col text-center',
leading: 'mb-2',
leadingIcon: 'size-8 shrink-0 inline-block',
title: 'text-xl text-pretty font-semibold text-highlighted',
description: 'mt-1 text-base text-pretty text-muted',
body: 'gap-y-6 flex flex-col',
providers: 'space-y-3',
checkbox: '',
select: 'w-full',
password: 'w-full',
otp: 'w-full',
input: 'w-full',
separator: '',
form: 'space-y-5',
footer: 'text-sm text-center text-muted mt-2'
}
}
}
})