Search code examples
javascriptvue.jsvue-componentvuejs3

How to access $children for creating Tabs component?


I'm trying to create a Tabs component in Vue 3 similar to this question here.

<tabs>
   <tab title="one">content</tab>
   <tab title="two" v-if="show">content</tab> <!-- this fails -->
   <tab :title="t" v-for="t in ['three', 'four']">{{t}}</tab> <!-- also fails -->
   <tab title="five">content</tab>
</tabs>

Unfortunately the proposed solution does not work when the Tabs inside are dynamic, i.e. if there is a v-if on the Tab or when the Tabs are rendered using a v-for loop - it fails.

I've created a Codesandbox for it here because it contains .vue files:

https://codesandbox.io/s/sleepy-mountain-wg0bi?file=%2Fsrc%2FApp.vue

enter image description here

I've tried using onBeforeUpdate like onBeforeMount, but that does not work either. Actually, it does insert new tabs, but the order of tabs is changed.

The biggest hurdle seems to be that there seems to be no way to get/set child data from parent in Vue 3. (like $children in Vue 2.x). Someone suggested to use this.$.subtree.children but then it was strongly advised against (and didn't help me anyway I tried).

Can anyone tell me how to make the Tab inside Tabs reactive and update on v-if, etc?


Solution

  • This solution was posted by @anteriovieira in Vuejs forum and looks like the correct way to do it. The missing piece of puzzle was getCurrentInstance available during setup

    The full working code can be found here:

    https://codesandbox.io/s/vue-3-tabs-ob1it

    I'm adding it here for reference of anyone coming here from Google looking for the same.