【问题标题】:Vue.js dynamic layout renderless component layout with multiple slots具有多个插槽的 Vue.js 动态布局无渲染组件布局
【发布时间】:2019-10-07 14:20:12
【问题描述】:

我正在尝试为我的应用程序构建动态布局。我有两种不同的布局,一种是DefaultLayout.vue:

<template>
  <div>
    <main>
      <slot/>
    </main>
  </div>
</template>

第二个是LayoutWithFooter.vue,有两个插槽:

<template>
  <div>
    <main>
      <slot/>
    </main>
    <footer>
      <slot name="footer"/>
    </footer>
  </div>
</template>

我处理动态布局的无渲染组件如下所示:

<script>
    import Vue from 'vue';
    import DefaultLayout from './DefaultLayout';
    import LayoutWithFooter from './LayoutWithFooter';

    export default {
        props: {
            name: {
                type: String,
                required: true
            }
        },
        created(){
            this.registerComponent("DefaultLayout", DefaultLayout);
            this.registerComponent("LayoutWithFooter", LayoutWithFooter);
            this.$parent.$emit('update:layout', this.name);
        },
        methods: {
            registerComponent(name, component) {
                if(!Vue.options.components[name]) {
                    Vue.component(name, component);
                }
            }
        },

        render() {
            return this.$slots.default[0];
        },
    }
</script>

所有这些都适用于DefaultLayout.vue,但是当我想使用LayoutWithFooter.vue 时,它无法处理其中的两个插槽。这是一个示例用法:

<template>
  <layout name="LayoutWithFooter">
    <div>
      <div>some content</div>
      <div slot="footer">content for the footer slot</div>
    </div> 
  </layout>
</template>

现在的问题是,“页脚槽的内容”没有呈现在 LayoutWithFooter.vue 的页脚槽内。

【问题讨论】:

  • 请分享详细的代码库,然后这个问题可能会得到建议。
  • 您是否尝试将&lt;div slot="footer"&gt; 移动为&lt;layout name="LayoutWithFooter"&gt; 的直接子代?
  • @c16n 我面临同样的问题。您找到解决方案了吗?

标签: vue.js


【解决方案1】:

首先,我希望您注意在示例中定义插槽级别。您提供了以下代码:

<template>
  <layout name="LayoutWithFooter">
    <div>
      <div>some content</div>
      <div slot="footer">content for the footer slot</div>
    </div> 
  </layout>
</template>

但实际上您的div slot="footer" 并不引用LayoutWithFooter.vue 组件的footer 插槽。因为无论如何,第一个孩子指的是default插槽。结果它看起来像:

“您想为default 插槽设置内容,并且在此default 插槽内您尝试为footer 插槽设置内容” - 但这是两个不同的范围。

下一个示例中的正确选项如下所示:

<template>
  <layout name="LayoutWithFooter">
    <!-- default slot content -->
    <div>
      <div>some content</div>
    </div>

    <!-- footer slot content -->
    <div slot="footer">content for the footer slot</div>
  </layout>
</template>

我根据您提供的代码和结构准备了一些示例。在那里,您可以切换布局并查看其工作原理,并在一个布局中使用不同的组件插槽。

在这里查看: https://codesandbox.io/s/sad-fog-zr39m

附:可能有些地方不完全清楚,请回复我的回答,我会尝试解释更多和/或为您提供更多链接和来源。

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 2015-01-21
    • 1970-01-01
    • 2019-02-27
    • 2018-02-07
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多