Component Events

Published on Sep 10, 2022

A way to communicate, out a component, events that happen or are triggered inside a component.

Given a component:

components/Product.js

app.component('product', {
  props: ['name', 'productId'],
  template: '<div>{{name}} <button>Add to card</button></div>'
})

Emitting an event

Inside the component, we can emit an event using the $emit method.

components/Product.js

app.component('product', {
  props: ['name', 'productId'],
  template: '<div>{{name}} <button @click="$emit(\'add-to-cart\', productId)">Add to card</button></div>'
})

or, using a method:

components/Product.js

app.component('product', {
  props: ['name', 'productId'],
  template: '<div>{{name}} <button @click="addToCart">Add to card</button></div>',
  methods: {
    addToCart() {
      this.$emit('add-to-cart', this.productId)
    }
  }
})

The first parameter is the name of the event, and the second is the data that we want to send. If multiple parameters need to be sent, they can be "packaged" as an object.

this.$emit('add-to-cart', {productId: this.productId, name: this.name})

Listening to an event

On the parent component, say Catalogue, we can listen to the event using the @event-name syntax.

components/Catalogue.js

app.component('catalogue', {
  props: ['products'],
  template: '<div>
    <product v-for="product in products" :key="product.id" :name="product.name" :productId="product.id" @add-to-cart="addProductToCart"></product>
  </div>',
  methods: {
    addProductToCart(productId) {
      console.log(productId)
    }
  }
})

Notice that, when listening, we don't specify the parameters. When the event is emitted, the parameters are passed to the method.

So, in the example above, the addProductToCart method will receive the productId as a parameter.