The Art of Passing Data Between Components

After this lesson you will be able to choose the right channel for every kind of data movement in a Vue 3 application. You will know when a value should be a prop, when it should be an emitted event, when v-model is the right abstraction, when provide and inject beat both - and when the reach for a global event bus is a mistake that will cost you an afternoon of debugging.

The one rule: props down, events up

A Vue component is a black box. It receives data from its parent through props and it reports back through events. It never reaches into its parent, and it never mutates what it was given.

      Parent
        |  props (data flows down)
        v
      Child
        |  events (news flows up)
        v
      Parent

That single diagram is the whole mental model. Everything else in this lesson is a detail of it.

Props: passing data down

defineProps declares the component’s public API. With the type-only syntax the prop types are checked at build time, and the compiler generates the runtime validation for you.

<script setup lang="ts">
interface User {
  id: number;
  name: string;
  role: 'admin' | 'member';
}

const props = defineProps<{
  user: User;
  compact?: boolean;
}>();
</script>

<template>
  <article :class="{ 'user-card--compact': compact }">
    <strong>{{ user.name }}</strong>
    <span>{{ user.role }}</span>
  </article>
</template>

withDefaults supplies fallbacks for optional props. The default for an object or an array must be a factory function, so that every instance gets its own copy - withDefaults(defineProps<{ items?: string[] }>(), { items: () => [] }).

Since Vue 3.5 you can destructure props directly and keep them reactive, because the compiler rewrites the destructuring into property accesses on the props object. On 3.4 and earlier, destructuring a prop loses reactivity; there you would use toRefs or read props.user directly.

The rule that is never broken

A component must never mutate its props. Mutating a nested property of a prop still mutates the parent’s state, which breaks one-way data flow and produces bugs that only appear under concurrency. The wrong version shifts an element out of props.items; the right version emits a remove event with the index and lets the parent decide what removing means.

<script setup>
const props = defineProps<{ items: string[] }>();
const emit = defineEmits<{ remove: [index: number] }>();

// Wrong: props.items.shift();
// Right: emit('remove', 0);
</script>

Events: reporting back up

defineEmits declares which events a component may emit. The type-only syntax uses a tuple list, where each tuple is the payload of one event.

<script setup lang="ts">
const emit = defineEmits<{
  search: [term: string];
  cancel: [];
}>();
</script>

<template>
  <form @submit.prevent="emit('search', 'vue')">
    <input type="search" />
    <button type="button" @click="emit('cancel')">Cancel</button>
  </form>
</template>

The parent listens with v-on, or @ for short. Event names are case-sensitive and, unlike component names, they are not automatically camelised, so a listener for update:modelValue must use that exact spelling. With the object syntax you can also attach a validator, which warns in development when the payload is not what you expect.

v-model: two-way binding built from props and events

v-model on a component is sugar. Underneath, it compiles to a prop named modelValue and an event named update:modelValue. Written by hand, the child is this:

<script setup>
defineProps<{ modelValue: string }>();
const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
</script>

<template>
  <input
    :value="modelValue"
    @input="emit('update:modelValue', $event.target.value)"
  />
</template>

A component can expose more than one model by giving each one a name. The prop is the name, the event is update: plus the name, so the parent writes v-model:title and v-model:body.

Since Vue 3.4, defineModel removes that boilerplate. It declares the model, wires the prop and the event, and hands you a writable reference.

<script setup lang="ts">
const model = defineModel<string>({ default: '' });
</script>

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

Modifiers work the same way. The parent writes v-model.trim; the child receives a modelModifiers prop describing what the parent asked for, and can honour it in a set option.

<script setup lang="ts">
const [model, modelModifiers] = defineModel({
  set(value) {
    return modelModifiers.trim ? value.trim() : value;
  },
});
</script>

provide and inject: sharing with a whole subtree

provide and inject let an ancestor hand a value to every descendant, without passing props through the components in between. It is the right tool for values that are relevant to a region of the tree - a theme, a locale, the current user, a form instance.

// Ancestor
import { provide, ref } from 'vue';

const locale = ref('en');
provide('locale', locale);

// Any descendant
import { inject } from 'vue';

const locale = inject('locale', 'en'); // 'en' is the fallback

The reactivity rule is the one people get wrong. Provide a ref, and the descendants that inject it share the same reactive reference, so mutating it in one place updates every consumer. Provide a plain value, and the descendants receive a snapshot that never changes again.

A plain value such as provide('theme', 'dark') is a snapshot, not a live binding.

Use a Symbol as the key when the value is not meant to be shared with unrelated code: a symbol key cannot collide with a string key, and it keeps the contract private between the provider and its consumers. If you inject without a default and no ancestor provided the value, Vue logs a warning and returns undefined.

The event bus: what Vue removed and what to use instead

Vue 2 let you create a shared emitter and publish to it from anywhere. Vue 3 removed the instance event API ($on, $off, $emit) precisely because it encouraged designs that are hard to follow.

An event bus still works if you install a tiny third-party emitter such as mitt or tiny-emitter:

// emitter.js
import mitt from 'mitt';

export const emitter = mitt();

// subscriber.js
import { onMounted, onUnmounted } from 'vue';
import { emitter } from './emitter';

export function useCartChanged(handler) {
  const onChanged = () => handler();
  onMounted(() => emitter.on('cart:changed', onChanged));
  onUnmounted(() => emitter.off('cart:changed', onChanged));
}

The pitfalls are worth stating explicitly, because the pattern still works and therefore still tempts people:

  1. Hidden dependencies. A component subscribes to a stringly-typed channel that appears nowhere in its props. Reading the component tells you nothing about what triggers it.
  2. Memory leaks. Every subscription must be removed on unmount. Forget the off call and the closure keeps a destroyed component alive.
  3. No payload contract. The event name is the only type information, so a typo in the channel name fails silently, at runtime, in production.
  4. Global ordering. Handlers run in registration order across the whole app, so behaviour depends on which component mounted first.
  5. Traceability. A bug report shows a publish call and a subscribe call in different files, with nothing connecting them.

Reach for an event bus only for genuinely app-wide, low-frequency notifications such as “the session expired”. For anything a component needs in order to render, use props, events or a store, where the dependency is visible in the code.

Two more channels

Slots let a parent inject markup into a child’s placeholder, which is how a component stays generic about its content; declare them with defineSlots when you want type safety. Fallthrough attributes are the attributes a parent puts on a component that the component does not declare as a prop: they land on the component’s single root element automatically, and inheritAttrs: false turns that off so you can place them yourself with v-bind="$attrs".

Pitfalls to remember

  • Mutating a prop, directly or through a nested object, breaks one-way data flow.
  • Destructuring props loses reactivity before Vue 3.5.
  • Event names are case-sensitive and are not auto-camelised.
  • Providing a plain value instead of a ref freezes the value for consumers.
  • An event bus creates dependencies that no file declares.
  • $attrs silently collects anything the component forgot to declare as a prop, so a typo in a prop name becomes a stray DOM attribute instead of an error.

Practice

A FilterBar sits above a ResultList. The filter bar holds a text query, a category dropdown and a sort selection, and the result list needs all three to fetch and sort. The results also report back how many items they found, and the filter bar should be able to clear the whole query in one action.

Decide the props, the events and the v-model bindings for each side, and explain why a shared store is the wrong answer here.

Vue 3PropsEmitsv-modelOne-Way Data Flow

Approach:

Both components are siblings, so there is no parent-child relationship to exploit. The natural owner is the component that holds the state - the filter bar - and the result list receives that state as props and reports results back through events. A store is unnecessary because both components already share a parent, and that parent can hold the state and pass it down.

Steps:

  1. Model the three filter values. The text query, the category and the sort order are all owned by the filter bar. Expose them to the parent with three named models: v-model:query, v-model:category, v-model:sort.
  2. Pass them down as props. The result list receives plain props: query, category, sort. Because they arrive in one direction, the list can read them freely without any risk of mutating the filter bar’s state.
  3. Report the count upward. The result list emits a count event with the number of matches, and the parent decides what to do with it.
  4. Implement “clear”. The filter bar emits a clear event; the parent resets the three refs in one place, and the filter bar’s inputs update automatically because they are bound with v-model to the parent’s refs.
  5. Avoid the store. A store would add a global dependency, outlive component lifetimes it has no business outliving, and make the data flow harder to follow than the two-component relationship already is.

Answer:

<!-- Parent.vue -->
<script setup>
import { ref } from 'vue';

const query = ref('');
const category = ref('all');
const sort = ref('relevance');
const total = ref(0);

function clear() {
  query.value = '';
  category.value = 'all';
  sort.value = 'relevance';
}
</script>

<template>
  <FilterBar
    v-model:query="query"
    v-model:category="category"
    v-model:sort="sort"
    @clear="clear"
  />
  <ResultList
    :query="query"
    :category="category"
    :sort="sort"
    @count="total = $event"
  />
  <p>{{ total }} results</p>
</template>

The filter bar declares three named models - defineModel<string>('query'), defineModel<string>('category') and defineModel<string>('sort') - plus defineEmits<{ clear: [] }>(), and binds its inputs to those models.

The result list declares defineProps<{ query: string; category: string; sort: string }>() and defineEmits<{ count: [total: number] }>(); it fetches and sorts from the props and reports the number of matches upward.

The rule that makes it all work: the parent owns the state, the filter bar edits it only through the models it declared, and the result list treats its props as read-only.

Found an issue with this content?

Tell us what could be improved.