我想访问插槽组件列表的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不是一个元素。
我目前的工作解决方案是使用指令&#39; update
和componentUpdated
挂钩中的vnode。但我想知道还有另外一种方法吗?
答案 0 :(得分:0)
您可以使用vm.$slots
访问插槽组件。这将返回一个对象,该对象的属性与命名的插槽相对应,默认插槽为default
。
例如:
beforeUpdate: function () {
this.$slots.default.forEach(item => {
console.log(item.data.key)
})
}