Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access $refs from other components not in the same level as current component

I'm working on a Vue application. It has a header and then the main content. Nesting and structure as below

TheHeader.vue -> TheLogin.vue

MainContent.vue -> ShoppingCart.vue -> OrderSummary.vue

I need to access an element in TheLogin.vue from OrderSummary.vue

this.$refs.loginPopover.$emit('open')

gives me an error "Cannot read property '$emit' of undefined" so obviously I am not able to access $refs from other components.

The question is how do I get hold of refs from other components? Thanks in advance!

Edit 1 - Found out $refs works with only child components. How do I access elements across components in different level?

like image 398
Vishwas Avatar asked Feb 15 '18 23:02

Vishwas


2 Answers

You definitely don't want to be reaching through the hierarchy like that. You are breaking encapsulation. You want a global event bus.

And here's a secret: there's one built in, called $root. Have your OrderSummary do

this.$root.emit('openPopup');

and set up a listener in your TheLogin's created hook:

this.$root.on('openPopup', () => this.$emit('open'));

In general, you should try to avoid using refs.

like image 181
Roy J Avatar answered Oct 16 '22 09:10

Roy J


For anyone who comes here later and wants to access $refs in parent component, not in this particular case for emitting events since event bus or a store would suffice but let's just say you want to access some element in parent to get it's attributes like clientHeight, classList etc. then you could access them like:

this.$parent.$parent.$refs //you can traverse through multiple levels like this to access $ref property at the required level
like image 28
Abdullah Sohail Avatar answered Oct 16 '22 11:10

Abdullah Sohail