106. Showing Alerts

npm create vue@latest


  1. 폼 완성 및 인증으로의 이동 전 마지막 최적화:

    • 사용자에게 제출 진행 중임을 알리는 메시지 표시 필요.
    • validate는 이를 위한 기능을 제공하지 않으므로 Tailwind를 사용하여 해결.
  2. 대기 메시지 렌더링 목표:

    • 폼 제출이 시간이 걸릴 수 있으므로 사용자에게 처리 중임을 알리는 메시지 렌더링.
  3. 알림 박스 구현:

    • 인증 컴포넌트 파일에서 알림 박스에 대한 데이터 생성.
    • 메시지 및 가시성을 관리하기 위한 속성(registrationSubmission, registrationShowAlert, registrationAlertVariant, registrationAlertMessage) 추가.
  4. 템플릿에 알림 박스 추가:

    • 등록 폼 상단에 div 태그를 추가하여 알림 박스 구현.
    • Tailwind 클래스를 사용하여 스타일링.
  5. 제출 버튼 비활성화:

    • 스팸 제출 방지를 위해 폼 제출 중에는 제출 버튼을 비활성화.
    • registrationInSubmission 속성을 사용하여 버튼 상태 관리.
  6. 등록 함수에서 데이터 업데이트:

    • register 함수에서 알림 및 버튼 상태 업데이트.
    • 초기 상태 설정 후 가상 응답으로 성공 메시지 설정.
  7. 브라우저에서 테스트 및 검토:

    • 변경 사항 저장 후 앱에서 폼 제출 테스트.
    • 성공 메시지 출력 및 버튼 비활성화 상태 확인.
  8. 사용자 경험 향상을 위한 상태 표시:

    • 제출 상태를 표시하는 알림 컴포넌트를 사용하여 사용자 경험 개선.
    • 제출 버튼 비활성화, 알림 표시, 변형 및 메시지 내용을 통해 제출 상태 커뮤니케이션.
    • 다음 강의에서는 로그인 폼 작업을 시작할 예정.
src/components/AppAuth.vue
<script setup lang="ts">
import useModal from '@/stores/modal'
import { storeToRefs } from 'pinia'
import { ref } from 'vue'

const modalStore = useModal()
const { hiddenClass, isOpen: modalVisibility } = storeToRefs(modalStore)

const tab = ref('login')

const schema = ref({
  name: 'required|min:3|max:100|alpha_spaces',
  email: 'required|min:3|max:100|email',
  age: 'required|min_value:18|max_value:100',
  password: 'required|min:9|max:100|excluded:password', // password 단어를 입력하면 유효성 검사를 통과할 수 없다.
  confirm_password: 'passwords_mismatch:@password', // 비밀번호 입력할 때, 비밀번호 재확인차 입력하는 필드 // 위의 password 부분과 일치하는지 확인함
  country: 'required|country_excluded:Antarctica',
  tos: 'required'
})

const userData = ref({
  country: 'USA'
})

const reg_in_submission = ref(false)
const reg_show_alert = ref(false)
const reg_alert_variant = ref('bg-blue-500')
const reg_alert_msg = ref('Please wait! Your acount is being created.')

const register = (values: {
  age: number
  confirm_password: string
  country: string
  email: string
  name: string
  password: string
  tos: number
}) => {
  // VeeForm 안에 VeeField의 모든 유효성 검사를 통과해야지 values 값이 들어온다.
  // ex.
  // {
  //  age: 31
  //  confirm_password: "asdf"
  //  country: "Germany"
  //  email: "sdf@sdf.com"
  //  name: "sfdf"
  //  password: "asdf"
  //  tos: "1"
  // }

  reg_show_alert.value = true
  reg_in_submission.value = true
  reg_alert_variant.value = 'bg-blue-500'
  reg_alert_msg.value = 'Please wait! Your account is being created.'

  reg_alert_variant.value = 'bg-green-500'
  reg_alert_msg.value = 'Success! Your account has been created.'
  console.log(values)
}
</script>

<template>
  <!-- Auth Modal -->
  <div class="fixed z-10 inset-0 overflow-y-auto" id="modal" :class="hiddenClass">
    <div
      class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
    >
      <div class="fixed inset-0 transition-opacity">
        <div class="absolute inset-0 bg-gray-800 opacity-75"></div>
      </div>

      <!-- This element is to trick the browser into centering the modal contents. -->
      <span class="hidden sm:inline-block sm:align-middle sm:h-screen">&#8203;</span>

      <div
        class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
      >
        <!-- Add margin if you want to see some of the overlay behind the modal-->
        <div class="py-4 text-left px-6">
          <!--Title-->
          <div class="flex justify-between items-center pb-4">
            <p class="text-2xl font-bold">Your Account</p>
            <!-- Modal Close Button -->
            <div class="modal-close cursor-pointer z-50" @click="modalVisibility = false">
              <i class="fas fa-times"></i>
            </div>
          </div>

          <!-- Tabs -->
          <ul class="flex flex-wrap mb-4">
            <li class="flex-auto text-center">
              <a
                class="block rounded py-3 px-4 transition"
                :class="{
                  'hover:text-white text-white bg-blue-600': tab === 'login',
                  'hover:text-blue-600': tab === 'register'
                }"
                href="#"
                @click.prevent="tab = 'login'"
              >
                Login
              </a>
            </li>
            <li class="flex-auto text-center">
              <a
                class="block rounded py-3 px-4 transition"
                :class="{
                  'hover:text-white text-white bg-blue-600': tab === 'register',
                  'hover:text-blue-600': tab === 'login'
                }"
                href="#"
                @click.prevent="tab = 'register'"
              >
                Register
              </a>
            </li>
          </ul>

          <!-- Login Form -->
          <form v-show="tab === 'login'">
            <!-- Email -->
            <div class="mb-3">
              <label class="inline-block mb-2">Email</label>
              <input
                type="email"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
                placeholder="Enter Email"
              />
            </div>
            <!-- Password -->
            <div class="mb-3">
              <label class="inline-block mb-2">Password</label>
              <input
                type="password"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
                placeholder="Password"
              />
            </div>
            <button
              type="submit"
              class="block w-full bg-purple-600 text-white py-1.5 px-3 rounded transition hover:bg-purple-700"
            >
              Submit
            </button>
          </form>
          <!-- Registration Form -->
          <div
            class="text-white text-center font-bold p-4 rounded mb-4"
            v-if="reg_show_alert"
            :class="reg_alert_variant"
          >
            {{ reg_alert_msg }}
          </div>
          <VeeForm
            v-show="tab === 'register'"
            :validation-schema="schema"
            @submit="register"
            :initial-values="userData"
          >
            <!-- Name -->
            <div class="mb-3">
              <label class="inline-block mb-2">Name</label>
              <VeeField
                type="text"
                name="name"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
                placeholder="Enter Name"
              />
              <ErrorMessage class="text-red-600" name="name" />
            </div>
            <!-- Email -->
            <div class="mb-3">
              <label class="inline-block mb-2">Email</label>
              <VeeField
                type="email"
                name="email"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
                placeholder="Enter Email"
              />
              <ErrorMessage class="text-red-600" name="email" />
            </div>
            <!-- Age -->
            <div class="mb-3">
              <label class="inline-block mb-2">Age</label>
              <VeeField
                type="number"
                name="age"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
              />
              <ErrorMessage class="text-red-600" name="age" />
            </div>
            <!-- Password -->
            <div class="mb-3">
              <label class="inline-block mb-2">Password</label>
              <VeeField name="password" :bails="false" #default="{ field, errors }">
                <input
                  type="password"
                  class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
                  placeholder="password"
                  v-bind="field"
                />
                <div class="text-red-600" v-for="error in errors" :key="error">
                  {{ error }}
                </div>
              </VeeField>
            </div>
            <!-- Confirm Password -->
            <div class="mb-3">
              <label class="inline-block mb-2">Confirm Password</label>
              <VeeField
                type="password"
                name="confirm_password"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
                placeholder="Confirm Password"
              />
              <ErrorMessage class="text-red-600" name="confirm_password" />
            </div>
            <!-- Country -->
            <div class="mb-3">
              <label class="inline-block mb-2">Country</label>
              <VeeField
                as="select"
                name="country"
                class="block w-full py-1.5 px-3 text-gray-800 border border-gray-300 transition duration-500 focus:outline-none focus:border-black rounded"
              >
                <option value="USA">USA</option>
                <option value="Mexico">Mexico</option>
                <option value="Germany">Germany</option>
                <option value="Antarctica">Antarctica</option>
              </VeeField>
              <ErrorMessage class="text-red-600" name="country" />
            </div>
            <!-- TOS -->
            <div class="mb-3 pl-6">
              <VeeField
                type="checkbox"
                name="tos"
                value="1"
                class="w-4 h-4 float-left -ml-6 mt-1 rounded"
              />
              <label class="inline-block">Accept terms of service</label>
              <ErrorMessage class="text-red-600 block" name="tos" />
            </div>
            <button
              type="submit"
              class="block w-full bg-purple-600 text-white py-1.5 px-3 rounded transition hover:bg-purple-700"
              :disabled="reg_in_submission"
            >
              Submit
            </button>
          </VeeForm>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>