构建自定义 Tabs 组件时无法在渲染函数中使用 TransitionGroup

Cannot use TransitionGroup in render function while building my custom Tabs component

正如我在标题中所写,我正在尝试构建自己的选项卡组件。到目前为止它是非常基础的:

Tabs.vue

setup(props, { slots }) {
  const { activeTab } = toRefs(props);
  provide("activeTab", activeTab);

  const newSlots = slots.default().map((slot, index) => {
    return h(slot, {
      index, // for each tab to know, whether is active
      key: index, // for TransitionGroup
    });
  });

  return () =>
    h(
      TransitionGroup,
      {
        name: "tabs-fade",
      },
      () => newSlots
    );
}

Tab.vue

<template>
  <div v-if="activeTab === index">
    <slot />
  </div>
</template>
setup() {
  const activeTab = inject("activeTab");

  return {
    activeTab,
  };
},

而且我计划这样使用它: Testing.vue

<ul>
  <li @click="activeTab = 0">1</li>
  <li @click="activeTab = 1">2</li>
  <li @click="activeTab = 2">3</li>
</ul>
<Tabs :activeTab="activeTab">
  <Tab> 1 </Tab>
  <Tab> 2 </Tab>
  <Tab> 3 </Tab>
</Tabs>

没有 TransitionGroup 一切正常,尽管当我尝试添加它以实现更平滑的过渡时,我在尝试在选项卡之间切换时遇到错误:

[Vue warn]: Unhandled error during execution of render function 
  at <TransitionGroup name="tabs-fade" > 
  at <Tabs activeTab=1 > 
  at <Testing> 
  at <App>

[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core 
  at <TransitionGroup name="tabs-fade" > 
  at <Tabs activeTab=1 > 
  at <Testing> 
  at <App>
Uncaught (in promise) TypeError: child.el.getBoundingClientRect is not a function

TransitionGroup 期望 children 的数量一致,以便它可以从一种状态转换到另一种状态。目前,Tabs.vue的根元素是有条件渲染的,当条件不满足时,可能根本没有元素,导致崩溃:

<!-- Tab.vue -->
<template>
  <div v-if="activeTab === index"> ❌ when false, no element exists
    <slot/>
  </div>
</template>

解决方案

div 上添加 v-else 以确保元素始终存在于 Tab.vue 中:

<!-- Tab.vue -->
<template>
  <div v-if="activeTab === index">
    <slot/>
  </div>
  <div v-else /> 
</template>

demo