1.1.3 ⢠Published 6 months ago
nuxt-mitter v1.1.3
Nuxt-mitter
Nuxt module for mitt library - enable fully typed events and autocompletion
šĀ Credits to developit author of the mitt library
Features
- ā Ā Nuxt 3 support
- š¤ Ā Easy to use composable
- š Ā auto-import - mitt provided by plugin
- ā»ļø Ā Optimized with Vue/Nuxt Lifecycle hooks
š¦Ā Install
Install nuxt-mitter
as dependency:
npm install nuxt-mitter
Add it to the modules
section of your nuxt.config.{ts|js}
:
modules: ['nuxt-mitter']
ā ļøĀ Optional - but strongly recommended
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
š Examples
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>
Types
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