按组件名称的Vue.js $ children

Fla*_*akx 25 javascript web-frameworks vue.js

我正试图通过名字访问一个特定的孩子.目前,由于孩子在哪里,我这样称呼孩子:

this.$root.$children[0]
Run Code Online (Sandbox Code Playgroud)

只要那个孩子总是[0]如此,那就没关系,但如果有办法可以做到这样的话会很棒:

this.$root.$children['detail']
Run Code Online (Sandbox Code Playgroud)

我一直在想$refs可能是我的问题的答案,但永远找不到它帮助我的方式.

有任何想法吗?

Lin*_*org 33

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

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

this.$refs.detailsChild
Run Code Online (Sandbox Code Playgroud)
<!-- Template of the parent component, assuming your child Component is called Details -->
<details v-ref:details-child></details>
Run Code Online (Sandbox Code Playgroud)

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

  • 对于使用Vue v2来到这里的人,你会在模板中设置`ref`属性,如:`<details ref ="detailsChild"> </ details>`.https://vuejs.org/v2/api/#ref (19认同)

dri*_*nor 25

您可以使用此属性:

this.$root.$children[0].$options.name
Run Code Online (Sandbox Code Playgroud)

例如:

this.$root.$children.find(child => { return child.$options.name === "name"; });
Run Code Online (Sandbox Code Playgroud)