Vue/Vue.js 문법

Vue.js 문법 - 컴포넌트 기초

IT Blue 2021. 7. 16. 00:52

 

컴포넌트

 

- 컴포넌트는 이름이 있는 재사용 가능한 인스턴스

 

예제

 

App.vue

<template>
  <MyBtn />
</template>
<script>
import MyBtn from '~/components/MyBtn'

export default {
  components: {
    MyBtn
  }
}
</script>

 

MyBtn.vue

<template>
  <div class="btn">
    Apple
  </div>
</template>
<style scoped>
  .btn {
    display: inline-block;
    margin: 4px;
    padding: 6px 12px;
    border-radius: 4px;
    background-color: gray;
    color: white;
    cursor: pointer;
  }
</style>

 

결과

 


 

컴포넌트 재활용

 

App.vue

<template>
  <MyBtn />
  <MyBtn />
  <MyBtn />
  <MyBtn />
</template>

 

결과

 

코드 이해하기

- 버튼 여러개가 화면에 출력

- 한번 만들어놓은 컴포넌트(Mybtn.vue)를 재활용

 


 

Props

 

- 컴포넌트에 데이터를 전달하기 위해 props 가 등장

- Props 는 컴포넌트에 등록할 수 있는 커스텀 속성

- 값이 props 속성에 전달되면, 그 값은 해당 컴포넌트 인스턴스의 속성이 됨

- 부모 컴포넌트와 자식 컴포넌트 간의 데이터 통신 방법 이라고도 부름

 


 

예제1 - 데이터 전달

 

App.vue

<!--
<template>
  <MyBtn color="royalblue" />
</template>
-->

<template>
  <MyBtn :color="color" />
</template>
<script>
import MyBtn from '~/components/MyBtn'

export default {
  components: {
    MyBtn
  },
  data() {
    return {
      color: 'royalblue'
    }
  }
}
</script>

 

MyBtn.vue

<template>
  <div 
    :style="{ backgroundColor: color }"
    class="btn">
    Apple
  </div>
</template>
<script>
export default {
  props: {
    color: {
      type: String,
      default: 'gray'
    }
  }
}
</script>

 

결과

 


 

예제2 - 클래스 추가

 

App.vue

<template>
  <MyBtn />
  <MyBtn large />
</template>

 

MyBtn.vue

<template>
  <div
    :class="{ large }"
    class="btn">
    Apple
  </div>
</template>
<script>
export default {
  props: {
    large: {
      type: Boolean,
      default: false
    }
  }
}
</script>
<style scoped lang="scss">
  .btn {
    display: inline-block;
    margin: 4px;
    padding: 6px 12px;
    border-radius: 4px;
    background-color: gray;
    color: white;
    cursor: pointer;
    &.large {
    font-size: 20px;
    padding: 10px 20px;
    }
  }
</style>

 

결과

 


 

예제3 - Slot

 

- 컴포넌트 사이에 있는 컨텐츠를 받아주는 태그

- 단순하게 텍스트만 받아서 출력하는 것이 아니라 예제에서 <MyBtn></MyBtn> 태그 사이에 있는 모든 내용을 <slot></slot>이라는 태그로 대체해서 넣어준다 (span 태그 안에 스타일까지 적용됨)

 

App.vue

<template>
  <MyBtn>Banana</MyBtn>
  <MyBtn :color="color">
    Apple
  </MyBtn>
  <MyBtn 
    large
    color="royalblue">
    Banana
  </MyBtn>
</template>

 

MyBtn.vue

<template>
  <div
    :class="{ large }"
    :style="{ backgroundColor: color }"
    class="btn">
    <slot></slot>
  </div>
</template>

 

결과