Reputation: 900
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.
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.
The cause could be any number of things, but here is what I thought was going on (in order)
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>
Upvotes: 2
Views: 5736
Reputation: 905
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.
Here is a working example that takes in few tabs components and shows only active tab component: https://jsfiddle.net/ajitid/eywraw8t/403667/
Upvotes: 2