为Vue中的每个<slot>分配一个父元素

3

我有一个Vue组件,名为my-component,代码如下:

<div class="outer">
    <div class="inner">
        <slot></slot>
    </div>
</div>

当我使用这个组件时:
<my-component>
    <p>This is paragraph 1 </p>
    <p>This is paragraph 2 </p>
</my-component>

生成的HTML应该是这样的(正常情况下):
<div class="outer">
    <div class="inner">
        <p>This is paragraph 1 </p>
        <p>This is paragraph 2 </p>
    </div>
</div>

但是,我正在寻找一种方法来制作类似于这样的东西:
<div class="outer">
    <div class="inner">
        <p>This is paragraph 1 </p>
    </div>
    <div class="inner">
        <p>This is paragraph 2 </p>
    </div>
</div>

我该如何将一个内部的div与每个slot元素关联起来?
1个回答

2

有一种方法是使用渲染函数而不是模板。通过这样做,您可以检查默认插槽的内容并根据需要包装内容。

这里是一个例子。

console.clear()

Vue.component("container",{
  template: "#container-template",
  render(h){
    // filter out things like carriage returns, spaces, etc
    const content = this.$slots.default.filter(c => !c.text)
    // build a list of wrapped content
    const wrapped = content.map(c => h('div', {attrs: {class:"inner"}}, [c]))
    // render the component
    return h("div", {attrs:{class:"outer"}}, wrapped)
  }
})

new Vue({
  el: "#app"
})
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
  <container>
    <p>This is paragraph 1 </p>
    <p>This is paragraph 2 </p>
  </container>
</div>


Bert,不是我不感激你的回答,但我正在寻找一个比使用渲染方法更简单的解决方案。是否可以使用命名插槽来解决这个问题?当然,感谢你的回答。目前,我会点赞这个答案。如果我没有得到其他解决方案,我会接受这个答案 :) - Tanmay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接