How to use Vue slot-scope with nested components

喜你入骨 提交于 2020-01-05 02:32:46

问题


I am struggling to know where to use the slot-scope attribute and make sense of the documentation.

Here's a simplified version of what I need to do. You can see it running here: https://jsfiddle.net/4j4zsy0g/

main code - simply use the repeater component with content to be repeated

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

repeater component

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

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

sample section

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

When rendered, this is the output. You can see that the sample content is only shown once.

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

And a warning message is displayed in the console:

Duplicate presence of slot "default" found in the same render tree - this will likely cause render errors.

What needs to be done to make this work correctly?


回答1:


The solution to this problem is to wrap the contents of the repeater in another element. That element needs to have an attribute slot-scope. The value of the attribute does not matter. The element can be template or any other element.

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

This can be seen in a jsFiddle by Simon Herteby.



来源:https://stackoverflow.com/questions/47893933/how-to-use-vue-slot-scope-with-nested-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!