결과 화면

 

1. BaseModal 컴포넌트 만들기

  • components/base/BaseModal.vue

<BaseModal> 컴포넌트는 여러 가지 모양의 모달에서 사용될 기본 틀이다.

  1. 모달의 경우, 주로 닫기 버튼과 제목, 내용 영역으로 구성되기 때문에 닫기 버튼과 <slot>으로 기본 레이아웃을 만든다.
  2. 모달 바깥쪽 영역과 닫기 버튼을 누르면 모달이 닫히는 이벤트가 필요하기 때문에 $emit 을 이용해 클릭 이벤트를 만든다.
  3. 공통으로 적용할 css/scss를 작성한다.
<template>
  <div
    class="base-modal"
    @click.self="$emit('close')">
    <div class="wrap">
      <BaseButton @click="$emit('close')">X</BaseButton>

      <div class="title">
        <slot name="title"/>
      </div>

      <div class="content">
        <slot name="content"/>
      </div>
    </div>
  </div>
</template>

<script>
import BaseButton from '@/components/base/BaseButton'

export default {
  name: 'BaseModal',

  components: {
    BaseButton
  }
}
</script>

<style lang="scss" scoped>
.base-modal {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.5);

  .wrap {
    position: relative;
    width: 90%;
    max-width: 500px;
    min-height: 300px;
    background-color: #fff;
    border-radius: 16px;

    .base-button {
      position: absolute;
      top: 20px;
      right: 20px;
      font-size: 20px;
      font-weight: 700;
    }

    .title {
      margin: 20px auto;

      h3 {
        font-size: 26px;
        font-weight: 700;
        text-align: center;
      }
    }

    .content {
      p {
        font-size: 16px;
      }
    }
  }
}
</style>

 

2. 필요한 modal 컴포넌트 만들기

  • components/modal/ModalCookie.vue

<slot>을 사용해 모달 안의 내용을 작성한다.

해당 방식으로 여러 가지 모달을 만들 수 있다.

<template>
  <BaseModal @close="$emit('close')">
    <h3 slot="title">Cookie Modal</h3>
    <p slot="content">쿠키 모달입니다.</p>
  </BaseModal>
</template>

<script>
import BaseModal from '@/components/base/BaseModal'

export default {
  name: 'ModalCookie',

  components: {
    BaseModal
  }
}
</script>

 

3. 페이지에 modal import 하기

  • pages/index.vue
  1. 만든 <ModalCookie> 컴포넌트를 import 시킨다.
  2. isModalCookie 속성을 만들어 v-if가 true 이면 모달이 나타나고, false 이면 모달이 사라지게 만든다. 
  3. ModalCookieToggle 클릭 이벤트를 만든다.
<template>
  <TheLayout>
    <BaseButton @click="ModalCookieToggle">쿠키 모달 열기</BaseButton>

    <ModalCookie
      v-if="isModalCookie"
      @close="ModalCookieToggle"/>
  </TheLayout>
</template>

<script>
import TheLayout from '@/components/layout/TheLayout'
import BaseButton from '@/components/base/BaseButton'
import ModalCookie from '@/components/modal/ModalCookie'

export default {
  name: 'Main',

  components: {
    TheLayout,
    BaseButton,
    ModalCookie
  },

  data() {
    return {
      isModalCookie: false
    }
  },

  methods: {
    ModalCookieToggle() {
      this.isModalCookie = !this.isModalCookie
    }
  }
}
</script>

+ Recent posts