Vue.js $children 按组件名称

新手上路,请多包涵

我正在尝试按名称访问特定的孩子。目前,由于孩子在哪里,我这样称呼孩子:

 this.$root.$children[0]

只要那个孩子总是 [0] 就可以了,但如果有办法做这样的事情那就太好了:

 this.$root.$children['detail']

我一直在想 $refs 可能是我的问题的答案,但永远找不到对我有帮助的方法。

有任何想法吗?

原文由 Flakx 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 393
2 个回答

您正在谈论的这个孩子真的是您想要访问它的组件的孩子吗?在这种情况下, v-ref 确实是答案:

 // in the code of the parent component, access the referenced child component like this:

this.$refs.detailsChild
 <!-- Template of the parent component, assuming your child Component is called Details -->
<details v-ref:details-child></details>

相关 API 文档:http: //vuejs.org/api/#v-ref

原文由 Linus Borg 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用此属性:

 this.$root.$children[0].$options.name

例如:

 this.$root.$children.find(child => { return child.$options.name === "name"; });

原文由 rjurado01 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题