Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 240
Luke Shaheen Avatar asked Mar 15 '17 15:03

Luke Shaheen


People also ask

How do you access child components at Vue?

To access child component's data from parent with Vue. js, we can assign a ref to the child component. And then we can access the child component data as a property of the ref. to assign the markdown ref to the markdown component.

How do you access a root component from a child instance in Vue?

Conclusion. We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.


2 Answers

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.

like image 73
Dan Gamble Avatar answered Sep 19 '22 12:09

Dan Gamble


You can access nested components data using $refs and if you want to access the refs inside of it you first have to target the first element of the first refs ([0])

example: parent.$refs[0].$refs.anAccount

like image 40
Abraham Duno Aguilera Avatar answered Sep 19 '22 12:09

Abraham Duno Aguilera