2
votes

Currently building a web page in Vue, and have hit a bit of an issue parsing and then rendering the <slot>'s child components.

I need to be able to take the slot, parse the components into an array, and then render those components for the end-user.

What I've Tried

I've tried many variations of things, most starting with this: this.$slots.default

This is the last version I tried

let slotComponents = [];
this.$slots.default.forEach(vNode => {
  slotComponents.push(vNode);
});

But I've also tried selecting the elements within the vNode and using things like $childeren to select the components. No luck so far.

Potential Issues

The cause could be any number of things, but here is what I thought was going on (in order)

  1. I'm not getting the components into the array properly
  2. I'm not rendering them properly or missed something about how they render
  3. Vue isn't supposed to do this?

Edit - Context

Seems like it would be easier if I gave you the full context of my specific problem.

Goal

To create a dynamic tab component. Should look like this.

// Example of component use
<tab-container>
  <tab>
    <!-- Tab Content -->
  </tab>
  <tab>
    <!-- Tab Content -->
  </tab>
  <tab>
    <!-- Tab Content -->
  </tab>
  <trash>
    <!-- This one won't show up -->
  </trash>
</tab-container>

In order to parse through this content, I needed to get the slot data out.

// Inside the <tabs-container> component
computed: {
  tabs: function() {
        let tabs = []
        this.$slots.default.forEach(vNode => {
            tabs.push(vNode);
        });
        return tabs;
    }
}


// Inside the <tabs-container> template
<div>
    {{tabs[currentTab]}}
</div>
1
in which hook are you using that , please provide more codeBoussadjra Brahim
Added a bit more context for you.Jacob
what are the errors, i think you need to add return tabs inside your computed propertyBoussadjra Brahim
It is in there, I just accidentally cut it off of the snippetJacob

1 Answers

2
votes

You shouldn't be using template and computed properties if you want to programmatically render out <tab> inside <tab-container>. {{}} in templates are designed to perform basic operations of JS. The most appropriate way will be to use render function.

Render functions - Vue docs

Here is a working example that takes in few tabs components and shows only active tab component: https://jsfiddle.net/ajitid/eywraw8t/403667/