2017-12-19 15 views
2

slot-scope属性を使用する場所を知り、ドキュメントを理解するのは難しいです。入れ子コンポーネントでVueスロットスコープを使用する方法

ここでは、私が行う必要がある簡単なバージョンです。 - 単に

<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> 

リピーター項目コンポーネントを繰り返しするコンテンツとrepeaterコンポーネントを使用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

関連する問題