1

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 ?

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.

And, there arises the need to understand how/why .$on(..) is made available in the framework. Thank you.

1 Answer 1

1

You can use the $on-method for implementation of CommunicationHub -- common mixin, for non parent <--> child communication (like in your case).

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

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

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.