【问题标题】:Wrap received slots (vnodes) in anonymous component in Vue.js在 Vue.js 的匿名组件中包装接收到的插槽(vnodes)
【发布时间】:2021-03-03 07:58:15
【问题描述】:

我想收到两个命名槽 slotOneslotTwo。它们位于 this.$scopedSlots.slotOnethis.$scopedSlots.slotTwo 的子组件中,并包含 vnode。如何将这些插槽(vnodes)包装在一个新组件中,以便我可以有条件地像这样渲染它们:

子组件:

<template>
  <div>
    <keep-alive>
      <component :is="wrapperComponentContainingProperSlot"></component>
    </keep-alive>
  </div>
</template>

父组件:

<template>
  <child>
    <template v-slot:slotOne>
      ...
    </template>
    <template v-slot:slotTwo>
      ...
    </template>
  </child>
</template>

我猜这个问题的核心是,如何从另一个组件内部的 vnodes 创建一个组件?

【问题讨论】:

  • slotOneslotTwo 应该在子组件中呈现在哪里?您没有在模板中的任何地方使用它们。
  • 可以的。但是,将&lt;component :is="wrapperComponentContainingProperSlot"&gt; 放在父级中会有什么好处呢?
  • 孩子正在尝试封装用于确定要渲染哪个插槽的逻辑(在我的情况下,基于我们是否在移动设备上运行),此外,我们还想添加keep-alive 每个插槽的功能。据我了解,这需要将 slotOneslotTwo 包装到它们自己的(匿名?)组件中——我只是不知道该怎么做,哈哈。

标签: javascript html vue.js vue-component


【解决方案1】:

我相信我希望实现这一点的动机是基于 &lt;keep-alive&gt; 在其父级被销毁时不会被销毁的错误前提。此情况并非如此。不过,我确实想出了如何将插槽包装到它们自己的组件中,包括匿名的和命名的。

子组件:

<template>
  <component :is="componentToRender"></component>
</template>

<script>
import Vue from 'vue';

export default {
  computed: {
    componentToRender() {
      return this.showSlotOnesGlobally
        ? new this.SlotOneWrapperComponent(this)
        : new this.SlotTwoWrapperComponent(this);
    },
  },
  /* Assume a parent further up in the tree provided this data */
  inject: {
    showSlotOnesGlobally: 'showSlotOnesGlobally'
  },
  methods: {
    SlotOneWrapperComponent(context) {
      return Vue.component('SlotOneContentWrapper', {
        render() {
          return context.$scopedSlots.slotOne();
        },
      });
    },
    SlotTwoWrapperComponent(context) {
      return Vue.component('SlotTwoContentWrapper', {
        render() {
          return context.$scopedSlots.slotTwo();
        },
      });
    },
  },
};
</script>

父组件:

<template>
  <child>
    <template v-slot:slotOne>
      ...
    </template>
    <template v-slot:slotTwo>
      ...
    </template>
  </child>
</template>

要使它们成为匿名组件,只需将 Vue.component('SlotOneContentWrapper', Vue.component('SlotTwoContentWrapper', 替换为 Vue.extend(

如果有人能提供更简洁的解决方案,那就太好了。

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 2020-06-05
    • 2021-04-03
    • 2017-12-20
    • 2021-11-25
    • 2018-11-26
    • 2019-08-11
    • 2017-07-13
    • 2020-10-01
    相关资源
    最近更新 更多