Lessons in this course (17)

8. Props, emits and v-model on components

Basic★ Must knowLesson 8 of 17
vue
<!-- ChildInput.vue -->
<script setup lang="ts">
const model = defineModel<string>({ required: true });     // Vue 3.4+: two-way binding helper
const props = withDefaults(defineProps<{ label: string; max?: number }>(), { max: 100 });
const emit = defineEmits<{ (e: "submit", value: string): void }>();
</script>
<template>
  <label>{{ label }} <input v-model="model" :maxlength="max" @keyup.enter="emit('submit', model)" /></label>
</template>

<!-- Parent.vue -->
<ChildInput v-model="search" label="Search" @submit="runSearch" />
  • One-way data flow: props flow down and are read-only in the child (Vue warns if you mutate them). To change data, emit an event or use v-model.
  • Prop validation (type, required, default, validator) or TypeScript types.
  • v-model on a component = modelValue prop + update:modelValue event (multiple: v-model:title).
  • Fallthrough attributes (class, id, listeners) apply to the root element (inheritAttrs: false + v-bind="$attrs" to control).