Is there no way to reliably handle slot contents in Vue 3?
P粉714844743
2023-08-30 08:47:17
<p>I'm currently migrating a Vue 2 codebase to Vue 3. </p>
<pre class="brush:php;toolbar:false;"><card>
<template #default>
<card-header>
<title level="3">Header</title>
</card-header>
<card-body
v-for="b in bodyCount"
:key="'b' b">
Body {{ b }}
</card-body>
<card-footer
v-for="f in footerCount"
:key="'f' f">
<text>Footer {{ f }}</text>
</card-footer>
</template>
</card></pre>
<p>The Card component has a render function that calls <code>this.$slots.default()</code>. However, in Vue 3 this returns different content than in Vue 2. So if I do <code>console.log(this.$slots.default())</code> - I get an array with 3 elements, [v node of type "header", type It is a v node of Symbol(Fragment), a v node of type Symbol(Fragment)]</p>
<p>More specifically, it doesn't recognize the card footer/card body as components, instead I see the symbol (fragment) in the type. Card-header is actually fine since it's not inside the v-for loop. </p>
<p>There is a logic inside the rendering function of the card component that needs to know how many text/footer components it has. So I need to be able to tell the component type. Is this not possible in Vue 3? I can guess this has something to do with the v-for here, but I'm not sure how to actually get the final v-nodes. In this example, I want the array to contain card headers all card bodies all card footers instead of 3 elements. </p>
The design of your card component doesn't look meaningful to me. I suggest you reconsider.
This is a simple playground rendering slot
Please heed the warning. Vue won't render
card-header
here because it can't parse it.If you have access to the data, why are you passing the
slots
actioncard-body
/card-footer
items directly throughbodyCount
?If it doesn't look reasonable to me.
It turns out - fragments can be expanded via the Children property on each element of the array. So in this case, v-for produces a v node, which is a fragment, but we can infer more by looking at the Children property.