简体   繁体   中英

Vue Slot: How to parse then render slot components

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>

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM