Vue.js 获取Vue'内每个组件的索引;s槽

Vue.js 获取Vue'内每个组件的索引;s槽,vue.js,Vue.js,假设我的组件中有以下模板接受任何类型的组件,无论是输入类型=文本,标签等 <template> <div :class="field"> <slot/> </div> </template> 如何从每个插槽组件获取索引或计数器?例如,第一个组件的索引为0,第二个组件的索引为1,以此类推 该索引对于Rails集成(如嵌套表单)非常有用,其中每个字段(Rails内)都需要索引 您可以使用$slots关键字获取插槽信息

假设我的组件中有以下模板<代码>接受任何类型的组件,无论是
输入类型=文本
标签

<template>
  <div :class="field">
    <slot/>
  </div>
</template>

如何从每个插槽组件获取索引或计数器?例如,第一个组件的索引为0,第二个组件的索引为1,以此类推


该索引对于Rails集成(如嵌套表单)非常有用,其中每个字段(Rails内)都需要索引

您可以使用
$slots
关键字获取插槽信息

例如,将其添加到组件的脚本部分

created() {
  console.log(this.$slots);
},
{
 // if you create named slot this will be the name of your slot instead
 // default is the name of default slot (same as your case)
 default: [
   // All the elements of the default slot will be there
   // Each entry is an element
   0: {
     ...
   },
   ...
 ]
}
您将获得一个包含组件所有插槽的对象

created() {
  console.log(this.$slots);
},
{
 // if you create named slot this will be the name of your slot instead
 // default is the name of default slot (same as your case)
 default: [
   // All the elements of the default slot will be there
   // Each entry is an element
   0: {
     ...
   },
   ...
 ]
}
我希望这将帮助您找到您想要的插槽信息


如果您需要更多关于
$slots
关键字的解释,请查看此页面

您能解释一下您想做什么吗?你需要索引做什么?谢谢!我补充了原因。“该索引对于Rails集成非常有用,比如嵌套表单,其中每个字段(Rails内)都需要索引。”谢谢!您的方法为我提供了组件数组,但没有提供索引。出于某种原因,this.$插槽包含未知的VNode。我使用.filter方法清除那些未知的vnode,并使用注入/提供方式将这个过滤后的数组传递给每个组件。您如何建议每个插槽组件知道其索引?再次遍历数组?因为如果我有100个插槽组件,我可能需要在同一个数组中迭代100次。或者您还有其他建议吗?再次感谢您帮助我前进。我认为您可以尝试遍历每个组件,并尝试查找组件id的
\uid
键。但是,组件的uid不是
0,1,…
它们由VueJS实例提供,可以完全不同,例如第一个组件的uid为33,第二个组件的uid为45。我认为您可以使用的方法是遍历slot元素数组,并使用该数组中提供的键
0,1,…
。此数组也按元素幻影排序。如果你有嵌套的元素,试着做一个递归函数。这个问题似乎意味着uid是不可检索的,我可以检索组件本身的uid。但是如何获取VNode的uid呢?我可以从控制台看到它,但无法检索它。我计划生成一个散列键/值,并将其更正。它可以通过
this.$parent.$children[0].uid获得