从与当前组件不同级别的其他组件访问 $refs

2022-01-25 00:00:00 javascript vue.js vue-component vuejs2

我正在开发一个 Vue 应用程序.它有一个标题,然后是主要内容.嵌套和结构如下

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

我需要从 OrderSummary.vue

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

给我一​​个错误 "Cannot read property '$emit' of undefined" 所以很明显我无法从其他组件访问 $refs.

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

问题是我如何从其他组件中获取 refs?提前致谢!

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

编辑 1 - 发现 $refs 仅适用于子组件.如何访问不同级别的组件中的元素?

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

推荐答案

你绝对不想像那样通过层次结构.你正在打破封装.你想要一个全局事件总线.

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

这里有个秘密:有一个内置的,叫做 $root.让你的 OrderSummary 做

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

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

并在 TheLogin 的 created 挂钩中设置一个监听器:

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

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

一般来说,你应该尽量避免使用 refs.

In general, you should try to avoid using refs.

相关文章