Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 27054  / 6 Years ago, thu, february 15, 2018, 12:00:00

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?


More From » vue.js

 Answers
3

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.


[#55133] Tuesday, February 13, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adilene

Total Points: 395
Total Questions: 88
Total Answers: 109

Location: Indonesia
Member since Tue, Aug 3, 2021
3 Years ago
;