[Vue+] Slot

INO·2022년 8월 6일
0

Vue

목록 보기
21/25
post-thumbnail

Resuablility, 재사용성

Slot

slot은 컴포넌트의 재사용성을 높여주는 기능입니다. 특정 컴포넌트에 등록한 하위 컴포넌트의 마크업을 확정하거나 재정의할 수 있습니다.

형식

/* Child Component*/
<template>
	<slot></slot>
    <div class="content">
    	 Content
    </div>
</template>

자식 Component에서 구체적인 태그를 정하지 않고 slot 태그로 남겨놓게 되면 부모 Component에서 따로 마크업을 재정의해서 사용할 수 있습니다.

/* Parent Component */
<template>
	<child-component>
    	<h1>First</h1>
    </child-component>
    
    <child-component>
    	<h2>Second</h2>
    </child-component>
    
    <child-component>
    	<h3>Third</h3>
    </child-component>
</template>
<script>
export default {
	components: {
    	"child-component": ChildComponent
    }
}
</script>

자식 Component에 각기 다른 HTML 코드를 적었습니다. slot 태그를 정의했기 때문에 해당 태그가 자식 컴포넌트의 slot 영역에 렌더링 되게 됩니다.

slot을 이용하면 특정 컴포넌트의 마크업 영역을 재정의하여 같은 컴포넌트를 각기 다르기 표현할 수 있습니다.

Named Slots

slot의 name을 사용하면 하나의 component에서 여러 개를 사용할 수 있습니다.

/* 부모 Component */
<template>
	<slot name="header"></slot>
    <slot name="content"></slot>
</template>

/* 자식 Component */
<template>
	<h1 v-slot:header></h1>
    <template v-slot:content">
    	<div class="content">
        </div>
    </template>
</template>

slot을 정의할 때 HTML 표준 태그르 사용하는 방법도 있지만 template 태그를 사용하는 방법도 존재합니다.

Scoped Slot

Slot은 컴포넌트 템플릿의 재사용성을 늘려주기 위한 기능이라면 Scoped Slot은 컴포넌트 데이터의 재사용성을 높여주는 기능입니다.

일반적으로 Vue에서는 props, 이벤트 발생을 제외하고는 다른 컴포넌트 값에 참조할 수 없습니다. 하지만 Scoped Slot은 하위 Component의 값을 상위 컴포넌트에서 접근하여 사용할 수 있습니다.

형식

Scoped Slotdㅡㄹ 사용하기 위해서는 부모, 자식 컴포넌트에 각자 코드가 필요합니다.

/* 자식 컴포넌트 */
<slot :상위 컴포넌트로 전달할 state 이름="하위 컴포넌트의 데이터"></slot>

/* 부모 컴포넌트 */
<child-component>
	<template slot-scope="임의의 변수">
    </template>
</child-component>

부모 Component에서 slot-scope라는 state로 하위 컴포넌트에서 올려보내준 데이터를 전달 받을 수 있습니다.

예시

/* Child Component */
<template>
	<div>
    	<h1>Child Component</h1>
        <slot :message="message"></slot>
    </div>
</template>
<script>
export default {
	data() {
    	return {
        	message: "Hello"
        }
    }
}
</script>

/* Parent Component */
<template>
	<div>
    	<child-component>
        	<template slot-scope="scopePros">
            	{{scopeProps.message}}
            </template>
        </child-component>
    </div>
</template>
<script>
import ChildComponent from "@/components/ChildComponent.vue";

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

예시를 보면 하위 컴포넌트에서 Scoped Slot으로 message 이름으로 state를 보냈기 때문에 상위 컴포넌트에서 scopeProps에 값을 받아 사용할 수 있게 되었습니다.

부모 컴포넌트에 정의한 slot-scope는 하위 컴포넌트에서 올려준 값을 받기 위한 임의의 변수입니다. scopeProps에는 하위 컴포넌트에서 올려준 값 message가 있습니다.

v-slot

v-slot은 Vue 2.6dㅔ서 새로 소개된 기능입니다. Named Slot과 Scoped Slot이 등장했습니다. 하지만 Vue 3.0에서부터 Scoped Slot이 사라지게 되었습니다.

왜냐하면 하위 컴포넌트의 HTML 요소를 상위 컴포넌트에서 정의하기 때문에 코드가 길어지며 함수를 작성할 때의 단일 책임 원칙(Single Responseibility Principle)을 위바하게 되었습니다.

단일 책임 원칙 : 하나의 컴포넌트는 하나의 역할을 할 수 있도록 한다.

v-slot 이점

slot을 사용하면 template 태그를 사용함으로써 장황해지는 표현을 간략하게 할 수 있어 코드의 가독성을 높일 수 있습니다.

profile
🎢

0개의 댓글