Vue.js:如何获取插槽的组件实例列表

问题描述 投票:0回答:2

我想访问插槽组件列表的 vue 实例。具体来说,我需要访问插槽组件的键或 id,以便我可以保留

beforeUpdate
updated
钩子中组件的状态。

我的组件模板如下:

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

因此,在我的父模板中,我将在此处传递组件列表。 例如。

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

或者也许:

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

甚至:

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

我的代码显然不起作用,因为它给了我一个 DOM 元素列表,也没有将 ref 附加到 slot,因为 slot 不是元素。 我当前的工作解决方案是在

update
componentUpdated
钩子中使用指令的 vnode。但我想知道还有其他方法吗?

vue.js vue-component ref slot
2个回答
4
投票

您可以使用

vm.$slots
访问插槽组件。这将返回一个对象,其属性对应于命名插槽和默认插槽的
default

例如:

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

0
投票

我在 stackoverflow 上的另一个答案中找到了解决方案,但我找不到这么快。但我使用了他的解决方案并制作了两个函数,第一个与我发现的相同,第二个添加了组件所在插槽的名称。这允许您找到安装在特定插槽中的子组件(因为我需要它)。

https://gist.github.com/erdesigns-eu/efb8d472684cabaa3573da65b97cf9d9

© www.soinside.com 2019 - 2024. All rights reserved.