props

props는 부모 컴포넌트의 데이터를 자식 컴포넌트로 전달한다.

부모 > 자식

 

emit

자식 컴포넌트에서 $emit 이벤트를 이용해 부모 컴포넌트에서 만들어 놓은 이벤트를 호출한다.

자식 > 부모

 

BaseButton 만들기

  1. BaseButton.vue 파일을 만들어 버튼을 공통으로 사용한다.
  2. class 속성을 props로 전달받아 css를 적용한다.
  3. $emit를 사용해 부모 컴포넌트에 작성한 이벤트를 호출한다.

 

결과 화면

 

1. BaseButton 컴포넌트 만들기

  • components/base/BaseButton.vue (자식 컴포넌트)
  1. :class="[color]" color 라는 속성을 만들어 부모 컴포넌트에서 색상 값을 전달받는다. (배열 형태로 만들면 여러 가지 값을 전달받을 수 있다.)
  2. <script> 태그 안 props 부분에 color에 대한 타입을 정의한다. (타입을 정의하지 않으면 잘못된 값을 전달받았을 때 콘솔 오류가 발생한다.)
  3. 전달받은 color에 대한 css를 작성한다. (.red, .blue)
  4. @click="$emit('click')" $emit을 이용해 클릭 이벤트를 호출한다. (클릭 이벤트는 부모 컴포넌트에 만든다.)
<template>
  <button
    type="button"
    :class="[color]"
    @click="$emit('click')">
    <slot/>
  </button>
</template>

<script>
export default {
  name: 'BaseButton',

  props: {
    color: {
      type: String,
      required: false
    }
  }
}
</script>

<style lang="scss" scoped>
button {
  width: 150px;
  height: 40px;

  &.red {
    background-color: red;
  }

  &.blue {
    background-color: blue;
  }
}
</style>

 

2. BaseButton 컴포넌트 사용하기

  • pages/index.vue (부모 컴포넌트)
  1. <BaseButton> 컴포넌트를 import 한다.
  2. <BaseButton> 컴포넌트에 color 속성을 작성한다. (color="red", color="blue")
  3. @click 메서드를 통해 클릭 이벤트를 호출한다.
  4. <script> 태그 안 methods 부분에 클릭 이벤트를 작성한다. (redAlert(), blueAlert())
<template>
  <TheLayout>
    <BaseButton
      color="red"
      @click="redAlert">
      빨간색 버튼
    </BaseButton>

    <BaseButton
      color="blue"
      @click="blueAlert">
      파란색 버튼
    </BaseButton>
  </TheLayout>
</template>

<script>
import TheLayout from "@/components/layout/TheLayout"
import BaseButton from "@/components/base/BaseButton"

export default {
  name: 'Main',

  components: {
    TheLayout,
    BaseButton
  },

  methods: {
    redAlert() {
      alert('빨간색 버튼')
    },

    blueAlert() {
      alert('파란색 버튼')
    }
  }
}
</script>

+ Recent posts