[Vuejs]-Vue – how to use an event handler to invoke functions from sibling/child

0👍

Typical way of handling sibling communication is to use an event hub, as you mentioned. It could be implemented in a number of ways.

One would be using a mixin, but you probably don’t need it. There is a simpler way of adding instance variables.

Demo below shows how such variable (representing an event hub) could be added and how it would be used to perform communication between sibling components, including the usage of Axios for an ajax (POST) request.

Vue.prototype.$hub = new Vue(); // use a Vue instance as event hub

Vue.component('get-component', {
  template: "#get-comp",
  data() {
    return {foo: 'initial foo'}
  },
  created() {
    this.$hub.$on('update', (eventData) => {
      this.foo = eventData;
      this.someMethod(eventData); // can also call methods
    });
  },
  methods: {
    someMethod(arg) { console.log('someMethod of get-component called with', arg); }
  }
});
Vue.component('add-component', {
  template: "#add-comp",
  methods: {
    addCoin() {
      axios.post('https://jsonplaceholder.typicode.com/posts', { // just a demo POST
        title: 'foo',
        body: 'bar',
        userId: 1
      }).then((response) => {
        this.$hub.$emit('update', response.data);
      });
    }
  }
})

new Vue({
  el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<template id="get-comp">
    <div>my foo is {{ foo }}</div>
</template>

<template id="add-comp">
    <div><button @click="addCoin">Click to emit foobar event</button></div>
</template>

<div id="app">
  <add-component></add-component>
  <get-component></get-component>
</div>

Leave a comment