Component Events
This page assumes you've already read the Components Basics. Read that first if you are new to components.
Emitting and Listening to Events
A component can emit custom events directly in template expressions (e.g. in a k-on
handler) using the built-in $emit
method:
<!-- MyComponent -->
<button @click="$emit('someEvent')">click me</button>
The parent can then listen to it using k-on
:
<MyComponent @some-event="callback" />
The .once
modifier is also supported on component event listeners:
<MyComponent @some-event.once="callback" />
Like components and props, event names provide an automatic case transformation. Notice we emitted a camelCase event, but can listen for it using a kebab-cased listener in the parent. As with props casing, we recommend using kebab-cased event listeners in templates.
TIP
Unlike native DOM events, component emitted events do not bubble. You can only listen to the events emitted by a direct child component.
Event Arguments
It's sometimes useful to emit a specific value with an event. For example, we may want the <BlogPost>
component to be in charge of how much to enlarge the text by. In those cases, we can pass extra arguments to $emit
to provide this value:
<button @click="$emit('increaseBy', 1)">
Increase by 1
</button>
Then, when we listen to the event in the parent, we can use an inline arrow function as the listener, which allows us to access the event argument:
<MyButton @increase-by="(n) => count += n" />
Or, if the event handler is a method:
<MyButton @increase-by="increaseCount" />
Then the value will be passed as the first parameter of that method:
function increaseCount(n) {
count.value += n
}
TIP
All extra arguments passed to $emit()
after the event name will be forwarded to the listener. For example, with $emit('foo', 1, 2, 3)
the listener function will receive three arguments.
Declaring Emitted Events
Emitted events can be explicitly declared on the component via the defineEmits()
macro :
<script setup>
defineEmits(['inFocus', 'submit'])
</script>
The $emit
method that we used in the <template>
isn't accessible within the <script setup>
section of a component, but defineEmits()
returns an equivalent function that we can use instead:
<script setup>
const emit = defineEmits(['inFocus', 'submit'])
function buttonClick() {
emit('submit')
}
</script>
The defineEmits()
macro cannot be used inside a function, it must be placed directly within <script setup>
, as in the example above.
If you're using an explicit setup
function instead of <script setup>
, events should be declared using the emits
option, and the emit
function is exposed on the setup()
context:
export default {
emits: ['inFocus', 'submit'],
setup(props, ctx) {
ctx.emit('submit')
}
}
As with other properties of the setup()
context, emit
can safely be destructured:
export default {
emits: ['inFocus', 'submit'],
setup(props, { emit }) {
emit('submit')
}
}
The emits
option also supports an object syntax, which allows us to perform runtime validation of the payload of the emitted events:
<script setup>
const emit = defineEmits({
submit(payload) {
// return `true` or `false` to indicate
// validation pass / fail
}
})
</script>
If you are using TypeScript with <script setup>
, it's also possible to declare emitted events using pure type annotations:
<script setup lang="ts">
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
</script>
More details: Typing Component Emits
Although optional, it is recommended to define all emitted events in order to better document how a component should work. It also allows Kdu to exclude known listeners from fallthrough attributes.
TIP
If a native event (e.g., click
) is defined in the emits
option, the listener will now only listen to component-emitted click
events and no longer respond to native click
events.
Events Validation
Similar to prop type validation, an emitted event can be validated if it is defined with the object syntax instead of the array syntax.
To add validation, the event is assigned a function that receives the arguments passed to the emit
call and returns a boolean to indicate whether the event is valid or not.
<script setup>
const emit = defineEmits({
// No validation
click: null,
// Validate submit event
submit: ({ email, password }) => {
if (email && password) {
return true
} else {
console.warn('Invalid submit event payload!')
return false
}
}
})
function submitForm(email, password) {
emit('submit', { email, password })
}
</script>
Usage with k-model
Custom events can also be used to create custom inputs that work with k-model
. Remember that:
<input k-model="searchText" />
does the same thing as:
<input
:value="searchText"
@input="searchText = $event.target.value"
/>
When used on a component, k-model
instead does this:
<CustomInput
:modelValue="searchText"
@update:modelValue="newValue => searchText = newValue"
/>
For this to actually work though, the <input>
inside the component must:
- Bind the
value
attribute to themodelValue
prop - On
input
, emit anupdate:modelValue
event with the new value
Here's that in action:
<!-- CustomInput.kdu -->
<script setup>
defineProps(['modelValue'])
defineEmits(['update:modelValue'])
</script>
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
Now k-model
should work perfectly with this component:
<CustomInput k-model="searchText" />
Another way of implementing k-model
within this component is to use a writable computed
property with both a getter and a setter. The get
method should return the modelValue
property and the set
method should emit the corresponding event:
<!-- CustomInput.kdu -->
<script setup>
import { computed } from 'kdu'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const value = computed({
get() {
return props.modelValue
},
set(value) {
emit('update:modelValue', value)
}
})
</script>
<template>
<input k-model="value" />
</template>
k-model
arguments
By default, k-model
on a component uses modelValue
as the prop and update:modelValue
as the event. We can modify these names passing an argument to k-model
:
<MyComponent k-model:title="bookTitle" />
In this case, the child component should expect a title
prop and emit an update:title
event to update the parent value:
<!-- MyComponent.kdu -->
<script setup>
defineProps(['title'])
defineEmits(['update:title'])
</script>
<template>
<input
type="text"
:value="title"
@input="$emit('update:title', $event.target.value)"
/>
</template>
Multiple k-model
bindings
By leveraging the ability to target a particular prop and event as we learned before with k-model
arguments, we can now create multiple k-model bindings on a single component instance.
Each k-model will sync to a different prop, without the need for extra options in the component:
<UserName
k-model:first-name="first"
k-model:last-name="last"
/>
<script setup>
defineProps({
firstName: String,
lastName: String
})
defineEmits(['update:firstName', 'update:lastName'])
</script>
<template>
<input
type="text"
:value="firstName"
@input="$emit('update:firstName', $event.target.value)"
/>
<input
type="text"
:value="lastName"
@input="$emit('update:lastName', $event.target.value)"
/>
</template>
Handling k-model
modifiers
When we were learning about form input bindings, we saw that k-model
has built-in modifiers - .trim
, .number
and .lazy
. In some cases, however, you might also want to add your own custom modifiers.
Let's create an example custom modifier, capitalize
, that capitalizes the first letter of the string provided by the k-model
binding:
<MyComponent k-model.capitalize="myText" />
Modifiers added to a component k-model
will be provided to the component via the modelModifiers
prop. In the below example, we have created a component that contains a modelModifiers
prop that defaults to an empty object:
<script setup>
const props = defineProps({
modelValue: String,
modelModifiers: { default: () => ({}) }
})
defineEmits(['update:modelValue'])
console.log(props.modelModifiers) // { capitalize: true }
</script>
<template>
<input
type="text"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
Notice the component's modelModifiers
prop contains capitalize
and its value is true
- due to it being set on the k-model
binding k-model.capitalize="myText"
.
Now that we have our prop set up, we can check the modelModifiers
object keys and write a handler to change the emitted value. In the code below we will capitalize the string whenever the <input />
element fires an input
event.
<script setup>
const props = defineProps({
modelValue: String,
modelModifiers: { default: () => ({}) }
})
const emit = defineEmits(['update:modelValue'])
function emitValue(e) {
let value = e.target.value
if (props.modelModifiers.capitalize) {
value = value.charAt(0).toUpperCase() + value.slice(1)
}
emit('update:modelValue', value)
}
</script>
<template>
<input type="text" :value="modelValue" @input="emitValue" />
</template>
For k-model
bindings with both argument and modifiers, the generated prop name will be arg + "Modifiers"
. For example:
<MyComponent k-model:title.capitalize="myText">
The corresponding declarations should be:
const props = defineProps(['title', 'titleModifiers'])
defineEmits(['update:title'])
console.log(props.titleModifiers) // { capitalize: true }