12
votes

I'm learning VueJS and I got a little confused on the ref, $refs lecture. I tried to understand it from vue's documentation, but I didn't get what I want to know.

If for example I have this component:

<user-item ref="details"></user-item>

and I get the data from this component using

this.$refs.details

to use that data in the User parent component, because this user-item is a child for User component.

<div id="User">
  <user-item ref="details"></user-item>
</div>

In the same time I have another component called, let's say Permissions that's child too, for User component:

<div id="User">
   <user-item ref="details"></user-item>
   <permissions></permissions> 
</div>

In this Permissions component I need the same this.$refs.details, but from what I test, like an experiment, doesn't work.

This is just a simple example.

Can someone please tell me how can I do it?

1

1 Answers

23
votes

You don't need to use $refs to pass data between components. Use data, props or dispatch events between components instead.

if you really want to access your user-item via $refs. Then you should do it like this from your permissions component.

this.$parent.$refs.details

It will basically get a reference to the parent (your User component) which has details in its $refs.

This assumes that your components are put together like this:

<user>
  <user-item ref="details"></user-item>
  <permissions></permissions>
</user>

Edit: $refs seems like it's empty when the component is being mounted, therefore, details will be undefined. Passing the whole $refs object to the permissions component's props seems to work with the OP.

<user>
  <user-item ref="details"></user-item>
  <permissions :parentRefs="$refs"></permissions>
</user>

Where parentRefs is a member in permissions component's props.

OP was able to access user-item from permissions using this.parentRefs.details.