gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:24:54 25 4
gpt4 key购买 nike

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

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

Screenshot of errors

最佳答案

TransitionGroup 需要一致数量的子级,以便它可以从一种状态转换到另一种状态。目前,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

关于javascript - 构建自定义 Tabs 组件时无法在渲染函数中使用 TransitionGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72158627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com