H
H
hckn2018-09-16 19:39:31
Vue.js
hckn, 2018-09-16 19:39:31

How to render slots in a list?

There is a component, in fact a list, where the slots must be filled with the actual items of the list.
There is a component, which is the subject of the list.
As a result, all items are rendered to the first element of the list. How to make each item go into a separate one li?
https://codesandbox.io/s/qzrwqppqqq

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-16
@hckn

To be honest, it's not very clear why there are slots at all. Pass data to the component as a normal parameter, and create a list based on it.
But if you still need to use the slot, write your own render function. That is, instead of the template that you have now, there will be something like

export default {
  render(h) {
    return h('ul', this.$slots['list-item'].map(n => h('li', [ n ])));
  },
};

UPD. If, in addition to the list itself, in the future it is planned to add some more elements to the List component, then it will probably not be very convenient to render the whole thing through a function, so you can write a small wrapper component for the slot elements:
components: {
  SlotWrapper: {
    functional: true,
    render: (h, context) => context.props.node,
  },
},

<li v-for="n in $slots['list-item']">
  <slot-wrapper :node="n"></slot-wrapper>
</li>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question