Skip to content
intermediate

Emits with TypeScript

Define and use typed custom events in Vue components.

<script setup lang="ts">
interface Props {
  modelValue: string
  label: string
}

const props = __________...

const emit = defineEmits<{
  'update:modelValue': [value: string]
  focus: []
  blur: []
  validate: [isValid: boolean, message?: string]
}>()

function handleInput(event: Event) {
  const target = event.target as HTMLInputElement
  emit('__________...', target.value)
}

const requiredMessage = 'Field is required'

function handleBlur() {
  emit('blur')
  const isValid = props.modelValue.length > 0
  emit('validate', __________...)
}

function handleFocus() {
  emit('focus')
}
</script>

<template>
  <input
    :value="modelValue"
    :placeholder="label"
    @input="handleInput"
    @focus="handleFocus"
    @blur="handleBlur"
  />
</template>
0/3 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code