emit is a small component function that forwards an event or command, with an optional payload, to the application’s dispatcher. It keeps user-input handlers shorter than calling dispatcher.dispatch() directly. section 5.2.4 section 11.2.4
Use emit to:
- Dispatch named commands such as update-current-todo or add-todo from event handlers. section 6.3.3
- Pass payloads when a handler needs data, such as edited text, an input value, or an item index. section 6.3.3
- Let components ignore the function when they do not dispatch commands. section 5.2.4
- Carry events upward from child components while props carry data downward from parents. section 11.0
Dispatching from a component
function CreateTodo({ currentTodo }, emit) { return h('input', { value: currentTodo, on: { input: ({ target }) => emit('update-current-todo', target.value) } }) } section 6.3.3
Listing 11.15 Emitting events from the component (component.js)
export function defineComponent({ render, state, ...methods }) {
class Component {
// --snip-- //
emit(eventName, payload) {
this.#dispatcher.dispatch(eventName, payload)
}
}
// --snip-- //
return Component
}
The component method delegates directly to its private dispatcher, preserving a concise public API for event handlers. section 11.2.4
