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 MittEvents = {
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 { fire } = useMitter()
const onClick = () => {
fire('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 FireFunction = <K extends keyof MittEvents>(event: K, payload?: MittEvents[K]) => void
export type EventHandlerFunction = <K extends keyof MittEvents>(
event: K,
handler: (payload: MittEvents[K]) => void
) => void
export type ListenFunction = <K extends keyof MittEvents>(
event: K,
handler: (payload: MittEvents[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.
*/
fire: FireFunction
/**
* 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