알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

vuejs slot-scope 대해서 본문

Web /Vue js tip

vuejs slot-scope 대해서

백곳 2018. 5. 14. 11:56
slot-scope 


개념은 부모 컴포넌트에서 slot을 사용할때 사용을 합니다. 


slot에 적용할  template 의 하위 자식 컴포넌트에서 부모의 자원(데이터)을  사용 하려고 할때 사용합니다. 


해당 내용은 예제를 통해서 하는것이 훨씬 직관적일 적 같습니다. 


<GridItem v-for="v in list"
:key="v.index"
:index="v.index"
:sort="v.sort"
:draggable="draggable"
:drag-delay="dragDelay"
:row-count="rowCount"
:cell-width="cellWidth"
:cell-height="cellHeight"
:window-width="windowWidth"
:row-shift="rowShift"
@dragstart="onDragStart"
@dragend="onDragEnd"
@drag="onDrag"
@click="click">
<slot name="cell"
:item="v.item"
:index="v.index"
:sort="v.sort"
:remove="() => { removeItem(v) }"/>
</slot>
</GridItem>



예를 들면 다음과 같은 코드가 있습니다. 


<GridItem
:draggable="true"
:sortable="true"
:items="items"
:height="100"
:width="100">
<template slot="cell" slot-scope="props">
<machine-icon :index= "props.index"
:settings="props.item"
/>
</template>
</GridItem >



다음과 같은 자식이 있습니다. 


여기서 중요한 부분만 보겠습니다. 


부모에서 의 slot 에서  :item와 :index 을 상속으로 내려 줍니다. 


<slot name="cell"
:item="v.item"
:index="v.index"
:sort="v.sort"
:remove="() => { removeItem(v) }"/>
</slot>


그럼 자식에서 템플릿을 만들때 


<template slot="cell" slot-scope="props">
<machine-icon :index= "props.index"
:settings="props.item"
/>
</template>


와 같이 slot-scope="props" 를 사용해서 자식  컴포넌트에서 해당 데이터를 받아서 사용할수 있게 됩니다. 


여기서 props 은 꼭 props 가 아니여도 됩니다. 


다른것으로 해도 매칭만 되면 상관없습니다. 


<template slot="cell" slot-scope="data">
<machine-icon :index= "data.index"
:settings="props.item"
/>
</template>


또한 똑같은 결과 입니다,


예제로 좋은 동영상 자료가 있어 첨부 합니다. 




Comments