A Guide on How to use Emit in Vue

In Vue, information is usually handed from dad or mum elements, to their youngsters in a uni-directional trend. That is transferred with props, that are the properties or attributes we give to components.

For instance, if we name a element PageOne, which has a prop referred to as title, that title property would change into obtainable throughout the PageOne element itself, letting us do what we wish to do with it. In that means, the information is handed right down to the kid element, after we declare it in a dad or mum element or web page:

In most situations, props enable us to do every little thing we have to do with information. Generally, nevertheless, we have to emit information upwards – from a baby element to its dad or mum. For this, we use $emit, which lets us ship information upwards, after which set off an occasion within the dad or mum element ought to an $emit occasion be fired.



How $emit works in Vue

There are 3 ways to fireside $emit in Vue, relying on in the event you’re utilizing the Choices API, Composition API, or inlining your $emit occasions. If you’re not sure, you can read about the difference between the Composition API and Options API here.

  • this.$emit throughout the Choices API.
  • $emit if utilized in your HTML template.
  • defineEmits and emit if used within the Composition API.

Let’s check out how this works, by a foolish instance. To illustrate we have now a counter element, which appears like this:

<template>
    <button @click on="$emit('counterEvent')">Click on Me</button>
</template>
Enter fullscreen mode

Exit fullscreen mode

This element is saved in a file referred to as Counter.vue. Our element cannot be modified because it’s used somewhere else, but it surely does have an $emit occasion fired any time it’s clicked. That is good, since we will use this in our dad or mum element.

So what if we wish to add this element someplace – for instance, in our App.vue file – and use it to show the worth of our counter. Let’s strive doing that now:

<template>
    <h1>{{ counter }}</h1>
    <Counter @counter-event="incrCounter"/>
</template>

<script>
import Counter from './Counter.vue'
export default {
    // Add our elements
    elements: {
      Counter
    },
    // Retailer our information
    information() {
        return {
            counter: 0
        }
    },
    strategies: {
        incrCounter: perform() {
            this.counter += 1;
        }
    }
}
</script>
Enter fullscreen mode

Exit fullscreen mode

Let’s break this down – initially, we embrace our Counter. Because it has an $emit occasion referred to as counterEvent, we will connect that to our Counter HTML. At any time when $emit fires, it will hearth the counterEvent, and thus the perform inside that property. Right here, we run incrCounter any time counterEvent fires.

By doing that, we additionally enhance our counter information by 1, since that’s what incrCounter does. As such, we have emitted the clicking occasion upwards to our dad or mum element.



Kebab Case

It’s possible you’ll discover that after we outlined our $emit occasion, we used camel case (counterEvent), however when monitoring the occasion, we used kebab case (counter-event).

In Vue 3 it’s high-quality to make use of counterEvent and counter-event interchangably since Vue 3 mechanically converts counterEvent to counter-event. In Vue 2, this performance doesn’t exist, so simply persist with counter-event for each.



Passing Information with $emit

To illustrate as a substitute, we would like our element to outline how a lot the counterEvent ought to enhance by. If we wish to do this, we will cross a second argument to the $emit perform, which is the worth:

<template>
    <button @click on="$emit('counterEvent', 2)">Click on Me</button>
</template>
Enter fullscreen mode

Exit fullscreen mode

Right here, we’re passing the worth 2 to our counterEvent. Let’s return to our App.vue file. To leverage this worth in counterEvent, we have to write it as a perform. Beneath, n is the worth:

<template>
    <h1>{{ counter }}</h1>
    <Counter @counter-event="(n) => incrCounter(n)"/>
</template>

<script>
import Counter from './Counter.vue'
export default {
    // Add our elements
    elements: {
      Counter
    },
    // Retailer our information
    information() {
        return {
            counter: 0
        }
    },
    strategies: {
        incrCounter: perform(worth) {
            this.counter += worth;
        }
    }
}
</script>
Enter fullscreen mode

Exit fullscreen mode

Now, our counter will enhance by the worth put within the baby element, permitting us to cross information to our dad or mum element as properly. As you’d anticipate, this isn’t restricted to simply numbers, however can embrace any information construction – together with objects and strings.



Utilizing $emit with the Choices API

We have proven a fairly easy instance, however we may even have written our Counter.vue baby element utilizing a perform as a substitute. Right here is an instance with the Choices API, utilizing this.$emit:

<template>
    <button @click on="emitFunction">Click on Me</button>
</template>

<script>
export default {
  emits: [ 'counterEvent' ],
    strategies: {
        emitFunction: perform() {
            this.$emit('counterEvent', 2)
        }
    }
}
</script>
Enter fullscreen mode

Exit fullscreen mode

This will likely show to be a barely cleaner means to make use of $emit, particularly if you wish to do different issues together with utilizing $emit each time a button is clicked.



Including your emit occasions to your prototype

It’s possible you’ll be aware that we additionally outlined our emit occasion in emits on the prototype. That is good apply for 2 causes:

  • It enables you to self-document the code by exhibiting which emit occasions are attainable on this element.
  • It helps you retain monitor of deprecated emits, since Vue will throw an error if an emit occasion is used however not discovered within the emits array.



Utilizing $emit with the Composition API

We are able to use $emit with the Composition API – the one distinction is we have now to make use of defineEmits as a substitute.

<template>
    <button @click on="emitFunction">Click on Me</button>
</template>

<script setup>
import { defineEmits } from 'vue'

const emit = defineEmits(['counterEvent']);
const emitFunction = perform() {
    emit('counterEvent', 2)
}
</script>
Enter fullscreen mode

Exit fullscreen mode

defineEmits is used to outline a full checklist of all permissible emit occasions. Right here, we solely have one, counterEvent. If you happen to had a couple of, you possibly can outline them as so:

const emit = defineEmits(['counterEvent', 'anotherEvent', 'finalEvent']);
Enter fullscreen mode

Exit fullscreen mode

If you happen to use an emit occasion not listed in defineEmits, Vue will throw a warning, much like utilizing emits on the Choices API. In any other case, you’ll be able to then use the emit() perform to emit as ordinary, without having to make use of the Choices API in any respect.



Closing Ideas and Finest Practices

Emit is a robust device for sending information again as much as the dad or mum when we have now to. It means datastreams may be two means in Vue. When defining emit code, the 2 important finest practices are:

  • All the time outline your emit occasions in both emits or defineEmits, which can allow you to hold your code clear and properly documented
  • Regular conference in Vue 3 is to make use of kebab case (this-is-kebab-case) for HTML, and camel case (thisIsCamelCase) in script. As such, it’s best to comply with this conference right here too.

I hope you’ve got loved this information on how $emit works. Keep tuned for extra Vue Content.

Add a Comment

Your email address will not be published. Required fields are marked *