vue.js - 如何将 Vue slot-scope 与嵌套组件一起使用

标签 vue.js vuejs2 vue-component

我很难知道在哪里使用 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/

相关文章:

vue.js - 组件已注册但未使用 vue/no-unused-components

vue.js - 如何在vue js中导入外部模板?

image - 在 vuejs 中的图像中包含路由器链接标签

javascript - Vue.js 2 - 使用事件中心从数组中删除项目

javascript - 从vue观察者获取长度值

javascript - 在模式 : 'history' vue router doesn't work 之后

node.js - NodeJS Elasticsearch 搜索返回 promise 而不是值

javascript - Vue 和 Jexcel 事件和计算字段

vue.js - 从 Quasar 启动文件访问存储

api - Vue.js - 从 ajax 调用加载组件