Nuxt module for mitt library - enable fully typed events and autocompletion
👏 Credits to developit author of the mitt library
- ✅ Nuxt 3 support
- 🤞 Easy to use composable
- 🔌 auto-import - mitt provided by plugin
- ♻️ Optimized with Vue/Nuxt Lifecycle hooks
Install nuxt-mitter
as dependency:
npm install nuxt-mitter
Add it to the modules
section of your nuxt.config.{ts|js}
:
modules: ['nuxt-mitter']
Provide your event.d.ts
file with type MitterEvents
:
export type MitterEvents = {
foo: string
bar?: string
}
Important
❗ Name of type must be MitterEvents
🚧 Improvements coming soon...
Add mitt
key to your nuxt.config.{ts|js}
and provide path to types
mitt: {
types: '...' //your path './types/eventTypes.d.ts'
}
🏁 That's it! You can now use My Module in your Nuxt app
Fire an event with the composable useMitter
<!--SayHello.vue-->
<script setup lang="ts">
const { emit } = useMitter()
const onClick = () => {
emit('hello', 'Hello 🫠🖖')
}
</script>
<template>
<button @click="onClick">
Say Hello
</button>
</template>
Listen to an event with the composable useMitter
<!--SomeWhereInTheComponentTree.vue-->
<script setup>
const { listen } = useMitter()
listen('hello', e => alert(e))
</script>
export type EmitFunction = <K extends keyof MitterEvents>(event: K, payload?: MitterEvents[K]) => void
export type EventHandlerFunction = <K extends keyof MitterEvents>(
event: K,
handler: (payload: MitterEvents[K]) => void
) => void
export type ListenFunction = <K extends keyof MitterEvents>(
event: K,
handler: (payload: MitterEvents[K]) => void
) => void
export interface UseMitterReturn {
/**
* Emits an event with an optional payload.
* @param event The event name to emit.
* @param payload Optional payload for the event.
*/
emit: EmitFunction
/**
* Registers an event handler.
* @param event The event name to listen for.
* @param handler The function to call when the event is emitted.
*/
on: EventHandlerFunction
/**
* Unregisters an event handler.
* @param event The event name to stop listening for.
* @param handler The function to remove from the event listeners.
*/
off: EventHandlerFunction
/**
* Registers an event handler and automatically removes it when the component is unmounted.
* @param event The event name to listen for.
* @param handler The function to call when the event is emitted.
*/
listen: ListenFunction
}
- Name: Nuxt-Mitter
- Package name: Nuxt-mitter
- Author: Gianluca Zicca
- Github: gianlucazicca
- Description: Nuxt module for mitt enable fully typed events and autocompletion
Local development
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Build the playground
npm run dev:build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Release new version
npm run release