[Vuejs]-Vue.js passing events up to parents in components

2👍

This is the type of problem vuex is designed to solve, however, before you consider adding an extra layer of complexity to your app, you may be able to get away with a simple global event bus, which is simply an empty Vue object to emit events onto, which can then be listened for by any component in your app, bypassing the parent-child chain:

const bus = new Vue({});

Vue.component('comp-1', {
  template: `<div>Comp 1 <button @click="emitClick">Click</button></div>`,
  methods: {
     emitClick(){
       bus.$emit('comp-1-click');
     }
  }
})


Vue.component('comp-2', {
  template: `<div><comp-1></comp-1></div>`,
})

new Vue({
  el: '#app',
  created(){
    bus.$on('comp-1-click',() => {
      console.log('Comp 1 clicked');
    });
  }
})

Here’s the JSFiddle: https://jsfiddle.net/oatLhzLp/

Leave a comment