Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

vue.js - Accessing nested child components in VueJS

Using v2.2.2. I have the following structure in my VueJS app. How can I access all of the Account components from a method on my Post component? The number of Accounts is dynamic - I want to grab all of the loaded Account components and iterate over them.

I know it's got something to do with $refs and $children, I just can't seem to figure out the right path.

<Root>
    <Post>
        <AccountSelector>
            <Account ref="anAccount"></Account>
            <Account ref="anAccount"></Account>
            <Account ref="anAccount"></Account>
        </AccountSelector>
    </Post>
</Root>
question from:https://stackoverflow.com/questions/42814406/accessing-nested-child-components-in-vuejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

http://vuejs.org/v2/guide/components.html#Child-Component-Refs

Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you have to assign a reference ID to the child component using ref. For example:

<div id="parent">
  <user-profile ref="profile"></user-profile>
</div>

var parent = new Vue({ el: '#parent' })
// access child component instance
var child = parent.$refs.profile

When ref is used together with v-for, the ref you get will be an array or an object containing the child components mirroring the data source.

Basically inside AccountSelector.vue you can do this.$refs.anAccount.map(account => doThingToAccount(account))

Edit The above answer is for accessing a direct child.

Currently there is no way to access a non direct parent / child component with $refs. The best way to get access to their data would be through events http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication or by using Vuex (Which i would recommend).

Non direct parent - child communication is very tricky without 1 of these 2 methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...