【问题标题】:Assigning a parent element for each <slot> in Vue为 Vue 中的每个 <slot> 分配一个父元素
【发布时间】:2017-08-27 21:22:15
【问题描述】:

我有一个 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>

如何将inner div 与每个slot 元素相关联?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

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

    这是一个例子。

    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,并不是我不欣赏你的回答,而是我正在寻找一个更简单的解决方案,而不是使用渲染方法。是否可以使用命名插槽来解决问题?当然,感谢您的回答。暂时,我赞成这个答案。如果我没有得到任何其他解决方案,我会接受答案:)
    猜你喜欢
    • 2011-08-19
    • 2015-03-17
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    相关资源
    最近更新 更多