728x90
 

 

Props

하나의 컴포넌트의 스타일을 가져와 루트 컴포넌트에 연결할 때 props에서 type과 default를 설정해둔다.

 

RootComponents.vue

<template>
  <MyBtn color="yellow"/>
  <MyBtn />
  <MyBtn />
</tempalte>

<script>
 import MyBtn from '~/components/MyBtn'
 
  export default {
   components: {
     MyBtn
   }
  }
</script>

 

MyBtn.vue

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

<script>
export default {
  props: {
    color: {
      type: String,
      default: 'gray'
    }  
  }
}
</script>

 

 

Provide Inject

Props의 단점은 중간매개체를 꼭 거쳐야 상속이 되기 때문에 5단계일 경우 모든 컴포넌트에 Props를 설정해야 하는 Props지옥이 생성된다. 이때 사용할 수 있는 것이 Provide인데 중간매개체를 거치지 않을 수 있지만 반응성을 유지하지는 않기 때문에 vue의 computed옵션을 가져와야 한다. 이 기능은 라이브러리를 사용해 개선할 수 있으니 개념 정도만 알아두자

 

App.vue > Parent.vue > Child.vue 에서 Provide, Inject할 때

//App.vue
<Parent :msg="message" />
// Parent.vue
<Child :msg="msg" />
// Child.vue
<div>inject:['msg']</div>
// App.vue
return {
  message: 'Hello!'
},
provide() {
  return {
    msg:this.message
  }
}
// Parent.vue
props: {
  msg: {
    type: String,
    defalut: ''
  }
}
// Child.vue
props: {
  msg: {
    type: String,
    defalut: ''
  }
}

 

Computed

반응성을 추가할 때

컴포넌트 기본 형태(빈 태그)로 사용하며 props는 사용할 필요가 없다.

// App.vue
import {computed} from 'vue'
// export default
provide() {
  return {
    msg: computed(() => this.message)
  }
}

// child.vue
<div>{{ msg.value }}</div>

 

 

Slot

하위 엘리먼트의 값을 포함

- 텍스트 삽입

<template>
  <div class="btn">
    <slot></slot>
  </div>
</template>
<MyBtn>Banana</MyBtn>

- style 적용

<MyBtn
  :color="color">
  <span style="color: red;">Banana</span>
</MyBtn>

 

Fallback Contents

slot내부에 대체 내용을 미리 정할 수 있다. 최상위 컴포넌트에서 내용을 수정 시 이는 대체된다.

Named Slots 

이름을 갖는 슬롯. slot 이름을 icon과 text로 지정해줬을 때, 최상위 컴포넌트에서 작성 순서와 상관없이 개별 컴포넌트에서 순서를 보장해icon->text 순으로 출력한다.

v-slot의 약어

<template #icon>(B)</template>

App.vue

<MyBtn>
  <template v-slot:text>Banana</template>
  <template v-slot:icon>(B)</template>
</MyBtn>

 

MyBtn.vue

<div class="btn">
  <slot name="icon"></slot>
  <slot name="text"></slot>
</div>

 

 

속성 상속

Attribute Inheritance

  • 루트 컴포넌트에 class를 추가하면 개별 컴포넌트에도 같은 class가 추가됨
  • template의 최상위요소가 2개 이상일 때는 속성이 상속되지 않음

 

속성을 상속하지 않을 때

export default {
  inheritAttrs: false
}

 

원하는 요소(h1)에 상속할 때

<h1 :class="$attrs.class"
  :style="$attrs.style">
</h1>

 

$attrs

원하는 요소(h1)에 attrs객체 데이터를 모두 상속할 때

<h1 v-bind="$attrs"></h1>

 

 

Emit

이벤트를 컴포넌트에 직접적으로 연결하는 방법

emit을 통해 부모 요소에 연결된 이벤트를 상속받아 실행하게 된다.

<h1 @click="$emit()">click</h1>
export default {
  emits: [
    'click' 
  ]
}
728x90
+ Recent posts