Vue3 Fundamentals ยท Vue 3 + TypeScript

Typing defineModel

Typed model

Typing defineModel

A component that supports v-model needs a prop for the value and an event for the update. In a <script setup lang="ts"> block defineModel declares both at once, and its type parameter says what the value is.

<script setup lang="ts">
const model = defineModel<string>();
</script>

<template>
  <input v-model="model" />
</template>

defineModel<string>() declares a modelValue prop of type string and an update:modelValue event carrying a string. The returned model is a ref-like value: read it, write it, and bind it with v-model.

The parent uses the component with v-model, and the type flows through. The value the parent binds must be a string, and the update it receives is a string, so a mismatch is caught at the call site. The generic is the only place the value's type is written, so the prop and the event cannot disagree.

In App.vue, bind the input to a defineModel<string>().

Challenge

The input ignores the model, so it never shows or updates the bound value. Export an App component from App.vue that declares const model = defineModel<string>() and binds the input with v-model="model".

The Test mounts your component with modelValue: 'Vue', checks the input's value, then types a new value and reads the emitted update. The starter renders a bare input, so the Test fails.

App.vue
<script setup lang="ts">
const model = defineModel<string>();
</script>

<template>
  <input />
</template>

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.