Vue.js Vue:访问渲染的命名插槽中的Vue组件方法

Vue.js Vue:访问渲染的命名插槽中的Vue组件方法,vue.js,vuejs2,reference,vue-component,vuejs-slots,Vue.js,Vuejs2,Reference,Vue Component,Vuejs Slots,如何访问在我的组件的命名插槽中呈现的Vue组件的功能 我的结构如下: ParentComponent.vue ... <util-component> <template v-slot:0> <child-component/> </template> <template v-slot:1> //Another component, and so on &

如何访问在我的组件的命名插槽中呈现的Vue组件的功能

我的结构如下:

ParentComponent.vue

...
<util-component>
      <template v-slot:0>
        <child-component/>
      </template> 
      <template v-slot:1>
        //Another component, and so on
      </template> 
</util-component>
...
...
<div v-for="(comp, index) in components" :key="index">
  <slot :name="index" ></slot>
</div>
...
...
methods: {
   myFunction () { // do something } 
}
...
UtilComponent
中,我想访问
ChildComponent
myFunction()
(当单击按钮时,所以不是在安装时)。我曾尝试在UtilComponent中使用
this.$slots[0]
,但它只给了我一个
VNode
,没有我需要的属性(数据和函数)<代码>此。$slots[0]。上下文提供完整的ParentComponent。使用
this.$slots[0][0].context.$children[0].$children[1]
我实际上可以访问ChildComponent及其函数,但这似乎非常迂回(获取渲染槽的父级,然后获取该父级的子级…)

是否有更好的方法从提供该插槽的组件(此处,
UtilComponent
)访问插槽内呈现的组件(此处,
ChildComponent
)?

您可以给它们一个类似的选项:


然后使用
this.$refs.child1.myFunction()
调用组件方法this.$children 您可以使用
中的
this.$children
访问其子组件

假设每个孩子都有一个名为
myMethod
的方法:

Vue.component('child-component'{
模板:`Child`,
方法:{
myMethod(){
console.log('hi')
}
}
})
中,您可以循环使用
此。$children
,它提供对开槽组件的访问,并且您可以在每个组件上访问该方法:

方法:{
访问儿童(){
//循环遍历每个子组件并调用其函数
这是$children.forEach(child=>{
child.myMethod();
});
}
}
<util-component>
      <template v-slot:0>
        <child-component ref="child1"/>
      </template> 
      <template v-slot:1>
        <child-component ref="child2"/>
      </template> 
</util-component>