【问题标题】:How can I wrap each element in a slot?如何将每个元素包装在插槽中?
【发布时间】:2017-12-11 12:22:00
【问题描述】:

我编写了一个组件(组件 B),它通过像这样的插槽接受自定义组件列表

// Component A
<div class="component-a">
  ...
  <component-b>
    <component-x></component-x>
    <component-y></component-y>
  </component-b>
  ...
</div>

我想将组件 x 和 y 包装在其他组件中,例如 li 标签。

// Output
...
<ul>
  <li><component-x></component-x></li>
  <li><component-y></component-y></li>
</ul>
...

我试过了

// Component B
<div class="component-b">
  <ul>
    <li v-for="item in $slots.default">
      <component :is="item"></component>
    </li>
  </ul>
</div>

它不起作用。该项目是 VNode 对象,它不能用组件标签呈现。有什么办法可以解决这个问题吗?

编辑:我的包装组件不是li标签,它是我在组件B中设置的具有指定props的自定义组件。如果我从组件A包装它们,我需要重复编写自定义组件及其props。

Edit2: Render 函数也许可以解决这个问题,但我正在寻找 html 模板(单文件组件)的解决方案。

【问题讨论】:

  • 也许这行得通 &lt;component :is="item.name"&gt;&lt;/component&gt; ,只是一个想法。因为 :is 需要一个组件名称而不是对象引用。

标签: vue.js vuejs2


【解决方案1】:

我想如果没有成人版 (render function) 就不可能做到这一点。

PS:对于更详细的组件,我建议插入另一个组件来处理其他功能,例如:

createElement(componentForMakeCoolThings,{props...})    

PS2:您可以通过简单的改编在单个文件组件中使用以下解决方案:

<script>
  export default{
     render: function(createElement){
     }
  }
</script>

Vue.component('makeLi',{
  render:function(createElement){
        var list = []
        this.$slots.default.forEach((element,index) => {
            if(element.tag){
                list.push(createElement('li',{},[element]))
                
            }
        });

        return createElement('ul',{},list)
    }

})

new Vue({el:'#app'});
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="app">
<make-li>
 <h1>test1</h1>
 <b>bold</b>
 <i>italic</i>
</make-li>


</div>

【讨论】:

  • 这个问题是keep-alive,transition即使不可见也会被包裹,v-if的标签被替换为cmets。
【解决方案2】:

这行得通吗?

<div class="component-a">
  <component-b>
    <component-x></component-x>
    <component-y></component-y>
  </component-b>
</div>

然后使用

<div class="component-a">
  <component-b>
    <ul>
      <li><component-x></component-x></li>
      <li><component-y></component-y></li>
    </ul>
  </component-b>
</div>

【讨论】:

  • 也许我的问题不清楚。我想将它们从组件 B 而不是 A 包装,因为我想通过具有指定道具的自定义组件包装它们。如果我将它们包装在组件 A 中,我需要多次使用 props 重复自定义组件。
猜你喜欢
  • 2020-12-16
  • 2020-06-09
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 2022-01-24
  • 2014-09-07
  • 2023-03-29
相关资源
最近更新 更多