2017-12-19 17 views
2

slot-scope 특성을 사용할 위치를 알고 설명서를 이해하는 데 어려움을 겪고 있습니다.중첩 된 구성 요소와 함께 Vue 슬롯 범위를 사용하는 방법

다음은 간단한 작업입니다. 반복 단순히 컨텐츠로 repeater 구성 요소를 사용

<repeater :ids="['a','b','c']"> 
    <h3>My Title</h3> 
    <another-component/> 
</repeater> 

리피터 구성 요소

<script id="repeater" type="text/x-template"> 
    <div class="repeater"> 
    <repeater-item v-for="id in ids" :key="id"> 
     <h2>Item {{id}}</h2> 
     <slot></slot> 
    </repeater-item> 
    </div> 
</script> 

리피터 항목의 구성 요소 - https://jsfiddle.net/4j4zsy0g/

주요 코드이 : 현재 실행 볼 수

<script id="repeater-item" type="text/x-template"> 
    <div class="repeater-item"> 
    <h1>Repeater Item</h1> 
    <slot></slot> 
    </div> 
</script> 

시료 부 렌더링

<script id="another-component" type="text/x-template"> 
    <div class="sample"> 
    Main content - should be in each repeater item 
    </div> 
</script> 

이 출력된다. 샘플 콘텐츠는 한 번만 표시됩니다.

<div class="repeater"> 
    <div class="repeater-item"> 
    <h1>Repeater Item</h1> 
    <h2>Item a</h2> 
    <h3>My Title</h3> 
    <div class="sample">Main content - should be in each repeater 
    item</div> 
    </div> 
    <div class="repeater-item"> 
    <h1>Repeater Item</h1> 
    <h2>Item b</h2> 
    <h3>My Title</h3> 
    </div> 
    <div class="repeater-item"> 
    <h1>Repeater Item</h1> 
    <h2>Item c</h2> 
    <h3>My Title</h3> 
    </div> 
</div> 

그리고 경고 메시지가 콘솔에 표시됩니다 : 같은 렌더링 트리에있는 슬롯 "기본"의

중복 존재 -이 오류를 렌더링 가능성의 원인이됩니다.

올바르게 작동하려면 어떻게해야합니까?

답변

1

이 문제의 해결책은 repeater의 내용을 다른 요소로 묶는 것입니다. 해당 요소에는 slot-scope 속성이 있어야합니다. 속성의 값은 중요하지 않습니다. 요소는 template 또는 다른 요소 일 수 있습니다.

<repeater :ids="['a','b','c']"> 
    <template slot-scope="x"> 
    <h3>My Title</h3> 
    <another-component/> 
    </template> 
</repeater> 

이것은 Simon Herteby가 jsFiddle에서 볼 수 있습니다.

+1

문제의 근본 원인은 문제의 코드가 가상 노드 (슬롯의 내용)를 복제하려고 시도한다는 것입니다. 범위가 지정된 슬롯은 구성 요소의 데이터 기능과 매우 유사하기 때문에 문제를 해결합니다. 슬롯은 각 반복마다 * 새로운 * 가상 노드 집합을 반환하는 함수로 바뀝니다. 다음은 훨씬 똑같은 일을하는 렌더링 함수 솔루션입니다. https://jsfiddle.net/4j4zsy0g/2/ – Bert