Vue 组件 .$on 用例 [英] Vue component .$on use case
问题描述
我不清楚如何使用 .$on(...) 方法在每个 Vue 实例中都可用.我确定我可能遗漏了一些用例,其中一个事件将由同一个 Vue 组件(?)发出和使用,但目前我无法想象很多.此外,该布线将在哪里进行.这会是生命周期方法吗?
Its not clear to me how to use the .$on(...) method available in every Vue instance. I am sure I am probably missing some use case where an event would be emitted and consumed by the same Vue component (?) but currently I am not able to imagine many. Also, where would this wiring be performed. Would that be in a lifecycle method ?
我的问题:我有不相关的(即非同级、非后代或非共同父级)组件,它们会根据在不同组件上进行的交互来更改视图.而且,$on(...) 似乎没有帮助我的目的.
My problem: I have unrelated (that is non-sibling, non-descendant or non-common-parent) components which change view based on interactions made on a different component. And, $on(...) does not seem to help my purpose.
而且,需要了解如何/为什么 .$on(..) 在框架中可用.谢谢你.
And, there arises the need to understand how/why .$on(..) is made available in the framework. Thank you.
推荐答案
您可以使用 $on
-method 来实现 CommunicationHub
-- 通用 mixin,对于非父 <--> 子通信(就像您的情况一样).
You can use the $on
-method for implementation of CommunicationHub
-- common mixin, for non parent <--> child communication (like in your case).
例如:您有两个 Vue 根应用程序:RootAppA
和 RootAppB
.要在它们之间进行通信,您可以使用下一个代码创建 CommunicationHub
mixin:
For example: you have two Vue root applications: RootAppA
and RootAppB
. To communicate between them, you can create CommunicationHub
mixin with next code:
let CommunicationHub = new Vue();
Vue.mixin({
data: function () {
return {
communicationHub: CommunicationHub
}
}
});
现在您可以通过使用 $emit
-method 从 RootAppA
发出自定义事件来发送数据,并通过在 RootAppB
中订阅此事件来获取此数据代码>,使用方法 $on
:
Now you can send data by emitting custom event from RootAppA
with $emit
-method, and get this data by subscribing on this event in RootAppB
, with method $on
:
let RootAppA = {
methods: {
sendData(){
this.communicationHub.$emit('customEvent', {foo: 'bar', baz: 1, comment: 'custom payload object'});
}
}
}
let RootAppB = {
created(){
this.communicationHub.$on('customEvent', (payload) => {
console.log(payload); //{foo: 'bar', baz: 1, comment: 'custom payload object'}
});
}
}
顺便提一下,CommunicationHub-pattern 对于较大的应用程序来说并不是那么灵活的解决方案.所以如果你的应用程序会长大,也许你会想要使用 Vuex-library (在之前的答案)
By the way, please mention that CommunicationHub-pattern is not so flexible solution for bigger apps. So if your application will grow up, perhaps you will want to use Vuex-library (see my example in previous so-answer)
这篇关于Vue 组件 .$on 用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!