Vis*_*was 4 javascript vue.js vue-component vuejs2
我正在开发一个Vue应用程序.它有一个标题,然后是主要内容.嵌套和结构如下
TheHeader.vue -> TheLogin.vue
MainContent.vue -> ShoppingCart.vue -> OrderSummary.vue
Run Code Online (Sandbox Code Playgroud)
我需要访问一个元素TheLogin.vue,从OrderSummary.vue
this.$refs.loginPopover.$emit('open')
Run Code Online (Sandbox Code Playgroud)
给我一个错误,"Cannot read property '$emit' of undefined"所以显然我无法$refs从其他组件访问.
问题是如何从其他组件中获取refs?提前致谢!
编辑1 - 发现$ refs仅适用于子组件.如何访问不同级别组件的元素?
Abd*_*ail 11
对于稍后来到这里并想要$refs在父组件中访问的任何人,在这种特殊情况下不适合发出事件,因为事件总线或存储就足够了,但我们只是说您想要访问父组件中的某些元素以获取其属性clientHeight,例如classList等。然后你可以像这样访问它们:
this.$parent.$parent.$refs //you can traverse through multiple levels like this to access $ref property at the required level
Run Code Online (Sandbox Code Playgroud)
你绝对不希望像这样通过层次结构.你破坏了封装.你想要一个全球事件总线.
这是一个秘密:有一个内置,称为$root.请你的OrderSummary做
this.$root.emit('openPopup');
Run Code Online (Sandbox Code Playgroud)
并在你的TheLogin的created钩子中设置一个监听器:
this.$root.on('openPopup', () => this.$emit('open'));
Run Code Online (Sandbox Code Playgroud)
通常,您应该尽量避免使用refs.
您可以在组件上放置这样的函数来执行此操作。我把我的放在 Mixin 中:
public findRefByName(refName) {
let obj = this
while (obj) {
if (obj.$refs[refName]) {
return obj.$refs[refName]
}
obj = obj.$parent
}
return undefined
}
Run Code Online (Sandbox Code Playgroud)
我还添加了一些访问器来提供帮助:
get mycomponent() {
return this.findRefByName('mycomponent')
}
Run Code Online (Sandbox Code Playgroud)
一旦存在,您只需执行以下操作即可访问您的组件:
this.mycomponent
Run Code Online (Sandbox Code Playgroud)