我很难知道在哪里使用 slot-scope
属性并理解文档。
这是我需要做的事情的简化版本。您可以在此处看到它正在运行:https://jsfiddle.net/4j4zsy0g/
主代码 - 只需使用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>
中继器项目组件
<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>
控制台中会显示一条警告消息:
Duplicate presence of slot "default" found in the same render tree - this will likely cause render errors.
需要做什么才能使其正常工作?
最佳答案
此问题的解决方案是将 repeater
的内容包装在另一个元素中。该元素需要有一个属性slot-scope
。属性的值并不重要。该元素可以是 template
或任何其他元素。
<repeater :ids="['a','b','c']">
<template slot-scope="x">
<h3>My Title</h3>
<another-component/>
</template>
</repeater>
这可以在 jsFiddle 中看到作者:西蒙·赫特比。
关于vue.js - 如何将 Vue slot-scope 与嵌套组件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47893933/