Vue.js - Documenting emitted events on your components

Emitting events from our components is a great way to notify the parent component about something that happened on the child and pass any additional data needed. It can get messy tho, from times to times.

This has been written specifically for Composition API but the same applies on Options too.

You can immediately emit events using the built-in $emit, but it would be great if we could see all the available emitted events on a component, just by visiting the SFC (aka .vue file). Especially when we are talking about larger components with multiple events.

<script setup>
const emit = defineEmits(['inFocus', 'submit', 'changed']);

// Example

function handleSubmit() {
  emit('submit', whateverData);
}

</script>

That's extremely easy to do and very helpful, especially on projects with multiple developers. A developer can have a lot more information about that component, just visiting the defineEmits place, instead of searching for $emit around the component. That way you document better how component works.

If you are using eslint, you can also enforce it on your team, using

'vue/require-explicit-emits': 1

rule under your eslint configuration file, on rules section.

Which is extremely cool. Always try your best to keep your codebase consistent.

Subscribe to Lioy

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe