Vue.js: How do I get a list of component instance for slot

Viewed 4129

I want to access vue instances of a list of slot components. Specifically I need to access the key or id of slot components so that I can preserve the state of components in beforeUpdate and updated hooks.

I have my component template as follows:

<div ref="items">
  <slot></slot>
</div>

so in my parent template, I'll pass in a list of components in here. eg.

<component>
  <button v-for="i in list" :key="i"></button>
</component>

or maybe:

<component>
  <another-el v-for="i in list" :key="i"></another-el>
</component>

or even:

<component>
  <button>foo<button>
  <button>bar<button>
  <button>baz<button>
</component>

my code obviously does not work as it gives me a list of DOM elements nor does attach ref to slot since slot is not an element. My current working solution is use directives' vnode in update and componentUpdated hooks. But I wonder is there another way to do it?

1 Answers

You can access slot components by using vm.$slots. This returns an object with properties corresponding to named slots and default for the default slot.

For instance:

beforeUpdate: function () {
  this.$slots.default.forEach(item => {
    console.log(item.data.key)
  })
}
Related