[Vuejs]-In Vue what is the best way to pass data from a child > parent > higher parent?

4πŸ‘

βœ…

I would recommend creating an event bus.

This can be done as follows:

In main.js add

Vue.prototype.$bus = new Vue

In your component

this.$bus.$emit('theEventName', data)

Real world example template

<button @click="$bus.$emit('theEventName', data)">Add</button>

Real world example in methods

methods: {
  addItem (data) {
    this.$bus.$emit('theEventName', data);
  }
}

In the parent (or anywhere in the app) add a listener

beforeCreate () {
  this.$bus.$on('theEventName', this.yourMethod);
}

methods: {
  yourMethod (data) {
    // do your thing
  }
}

Don’t forget to remove the listener

beforeDestroy(){
  this.$bus.$off('theEventName', this.yourMethod);
}
πŸ‘€Tim Wickstrom

Leave a comment