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