Vue.js Components Events


Example

One of the ways components can communicate with its ancestors/descendants is via custom communication events. All Vue instances are also emitters and implement a custom event interface that facilitates communication within a component tree. We can use the following:

  • $on: Listen to events emitted by this components ancestors or descendants.
  • $broadcast: Emits an event that propagates downwards to all descendants.
  • $dispatch: Emits an event that triggers first on the component itself and than propagates upwards to all ancestors.
  • $emit: Triggers an event on self.

For example, we want to hide a specific button component inside a form component when the form submits. On the parent element:

var FormComponent = Vue.extend({
  // ...
  components: {
    ButtonComponent
  },
  methods: {
    onSubmit () {
        this.$broadcast('submit-form')
    }
  }
})

On the child element:

var FormComponent = Vue.extend({
  // ...
  events: {
    'submit-form': function () {
        console.log('I should be hiding');
    }
  }
})

Some things to keep in mind:

  • Whenever an event finds a component that is listening to it and gets triggered, it will stop propagating unless the function callback in this component returns true.
  • $dispatch() always triggers first on the component that has emitted it.
  • We can pass any number of arguments to the events handler. Doing this.$broadcast('submit-form', this.formData, this.formStatus) allows us to access this arguments like 'submit-form': function (formData, formStatus) {}