从与当前组件不在同一级别的其他组件访问 $refs [英] Access $refs from other components not in the same level as current component

查看:22
本文介绍了从与当前组件不在同一级别的其他组件访问 $refs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 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.

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

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'));

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

In general, you should try to avoid using refs.

这篇关于从与当前组件不在同一级别的其他组件访问 $refs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆