【问题标题】:How to use Vue slot-scope with nested components如何将 Vue 插槽范围与嵌套组件一起使用
【发布时间】:2017-12-19 19:27:42
【问题描述】:

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

repeater-item 组件

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

并在控制台中显示警告消息:

在同一渲染树中发现重复的“默认”插槽 - 这可能会导致渲染错误。

需要做什么才能使这项工作正常进行?

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案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 中看到。

    【讨论】:

    • 问题的根源(其中一部分)是问题中的代码试图复制虚拟节点(插槽的内容)。作用域槽解决了这个问题,因为作用域槽的工作方式与组件中的数据函数非常相似;插槽变成了一个函数,该函数为每次迭代返回一组 new 虚拟节点。这是一个渲染函数解决方案,它做了很多相同的事情。 jsfiddle.net/4j4zsy0g/2
    猜你喜欢
    • 2019-06-08
    • 2021-02-06
    • 2018-07-28
    • 2021-03-07
    • 2019-10-27
    • 1970-01-01
    • 2019-06-08
    • 2019-07-27
    • 2018-08-27
    相关资源
    最近更新 更多