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

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

本文介绍了从与当前组件不同级别的其他组件访问 $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.

问题是我如何从其他组件中获取 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.

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

本文标题为:从与当前组件不同级别的其他组件访问 $refs

基础教程推荐