3

如何访问在组件的命名槽内呈现的 Vue 组件的功能?

我有以下结构:

父组件.vue

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

实用组件.vue

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

子组件.vue

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

UtilComponent中,我想访问ChildComponent's myFunction()(单击按钮时,不在安装时)。我曾尝试this.$slots[0]在 UtilComponent 中使用,但它只给我一个VNode没有我需要的属性(数据和函数)。this.$slots[0].context给了我完整的 ParentComponent。有了this.$slots[0][0].context.$children[0].$children[1]我实际上可以访问 ChildComponent 及其功能,但这似乎很迂回(获取渲染插槽的父级然后获取该父级的子级的子级......)

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

4

2 回答 2

2

this.$children

您可以使用this.$childrenfrom<util-component>访问其开槽的子组件。

想象一下,每个孩子都有一个名为的方法myMethod

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

<util-component>中,您可以遍历this.$children,这可以访问开槽组件,并且您可以在每个组件上访问该方法:

methods: {
  accessChildren() {
    // Loop through each child component and call its function
    this.$children.forEach(child => {
      child.myMethod();
    });
  }
}
于 2021-02-03T10:42:52.280 回答
2

你可以给他们一个像这样的参考

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

然后this.$refs.child1.myFunction()用来调用组件方法

于 2021-02-03T08:56:57.540 回答