Klausette
Klausette

Reputation: 412

Vue: Access Vue component method inside rendered named slot

How can I access the functions of a Vue Component that is rendered inside a named slot of my component?

I have the following structure:

ParentComponent.vue

...
<util-component>
      <template v-slot:0>
        <child-component/>
      </template> 
      <template v-slot:1>
        //Another component, and so on
      </template> 
</util-component>
...

UtilComponent.vue

...
<div v-for="(comp, index) in components" :key="index">
  <slot :name="index" ></slot>
</div>
...

ChildComponent.vue

...
methods: {
   myFunction () { // do something } 
}
...

In UtilComponent, I want to access ChildComponent's myFunction() (when clicking on a button, so not at mounted). I have tried using this.$slots[0] in UtilComponent but it's only giving me a VNode without the attributes I need (data and functions). this.$slots[0].context gives me the full ParentComponent. With this.$slots[0][0].context.$children[0].$children[1] I can actually get to ChildComponent and its functions, but this seems very roundabout (getting the parent of the rendered slot to then get the child of the child of that parent...)

Is there a better way of accessing a component('s functions) rendered inside a slot (here, ChildComponent) from the component which provides that slot (here, UtilComponent)?

Upvotes: 3

Views: 2162

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could give them a ref like :

<util-component>
      <template v-slot:0>
        <child-component ref="child1"/>
      </template> 
      <template v-slot:1>
        <child-component ref="child2"/>
      </template> 
</util-component>

then use this.$refs.child1.myFunction() to call the component method

Upvotes: 1

Dan
Dan

Reputation: 63059

this.$children

You can use this.$children from <util-component> to access its slotted child components.

Imagine that each child had a method called myMethod:

Vue.component('child-component', {
  template: `<div class="child">Child</div>`,
  methods: {
    myMethod() {
      console.log('hi')
    }
  }
})

In <util-component>, you can loop through this.$children, which gives access to the slotted components, and you can access that method on each one:

methods: {
  accessChildren() {
    // Loop through each child component and call its function
    this.$children.forEach(child => {
      child.myMethod();
    });
  }
}

Upvotes: 3

Related Questions