Vue components and templates: SFCs, props, slots
A Vue application is a tree of components, each usually written as a single-file component (SFC): one .vue file holding its logic, its HTML-based template and optionally its styles. This page covers how those pieces fit together: the SFC format and <script setup>, the template syntax and directives, how components talk to each other through props, emitted events and v-model, and how slots let a parent pass markup into a child. The examples build the order screen of OrdersPortal, an invented back-office app.
The samples target Vue 3.5 (3.5.45 is current; 3.6 is in release-candidate stage). Each component was compiled with @vue/compiler-sfc, bundled with esbuild, mounted into a jsdom document in Node.js 22 by the small main.js driver shown with it, and the printed HTML is shown as output. In a real project the same files are built by Vite, created with npm create vue@latest.
Topics on this page
Section titled “Topics on this page”| Topic | Use it to |
|---|---|
| Single-file components and templates | Write a component and use interpolation, bindings, events, conditionals and lists. |
| Props, emits and v-model | Pass data down, send events up and bind values two ways. |
| Slots | Let parents supply markup to layout and list components. |
Single-file components and templates
Section titled “Single-file components and templates”An SFC has up to three blocks. <script setup> holds the component logic using the Composition API; every top-level variable, function and import in it is available to the template, so there is no return or export default. <template> holds HTML extended with Vue syntax, which the compiler turns into an optimized render function at build time. <style scoped> holds CSS that applies only to this component. Add lang="ts" to the script block to write TypeScript. The older Options API (data, methods, computed objects) is still supported, but new code and this section use <script setup>.
Templates use {{ }} for text interpolation and directives for everything else. v-bind:attr, shortened to :attr, binds an attribute or prop to an expression; :class and :style also accept objects and arrays. v-on:event, shortened to @event, attaches an event listener, with modifiers such as @submit.prevent. v-if, v-else-if and v-else add or remove elements; v-show only toggles display. v-for="item in items" repeats an element and needs a unique :key. Refs created with ref() are unwrapped automatically in the template, so you write order.id, not order.value.id.
<script setup>import { ref } from 'vue'
const order = ref({ id: 1001, status: 'open', customer: { name: 'Ada Lopez', email: 'ada@example.test' }, lines: [ { sku: 'SKU-RED-01', name: 'Red mug', quantity: 2 }, { sku: 'SKU-BLU-07', name: 'Blue coaster', quantity: 12 }, ],})const showEmail = ref(false)
function markShipped() { order.value.status = 'shipped'}</script>
<template> <article :id="`order-${order.id}`" :class="['order', order.status]"> <h2>Order {{ order.id }} for {{ order.customer.name }}</h2> <p v-if="showEmail">{{ order.customer.email }}</p> <button v-else type="button" @click="showEmail = true">Show email</button> <ul> <li v-for="line in order.lines" :key="line.sku">{{ line.quantity }} x {{ line.name }}</li> </ul> <button type="button" :disabled="order.status !== 'open'" @click="markShipped">Mark shipped</button> </article></template>// main.js - mounts the component in a jsdom document and clicks both buttons.import { createApp, nextTick } from 'vue'import OrderSummary from './OrderSummary.vue'
createApp(OrderSummary).mount('#app')const html = () => console.log(document.querySelector('#app').innerHTML)html()document.querySelector('button').click() // "Show email"await nextTick() // Vue batches DOM updatesdocument.querySelector('button').click() // "Mark shipped" is now the only buttonawait nextTick()html()Output:
<article id="order-1001" class="order open"><h2>Order 1001 for Ada Lopez</h2><button type="button">Show email</button><ul><li>2 x Red mug</li><li>12 x Blue coaster</li></ul><button type="button">Mark shipped</button></article><article id="order-1001" class="order shipped"><h2>Order 1001 for Ada Lopez</h2><p>ada@example.test</p><ul><li>2 x Red mug</li><li>12 x Blue coaster</li></ul><button type="button" disabled="">Mark shipped</button></article>Changing order.value.status was enough to update the class list and disable the button: the template is a function of reactive state, covered in depth in Reactivity and state.
Pitfalls:
v-ifandv-foron the same element.v-ifruns first and cannot see the loop variable; filter with a computed property or wrap in a<template v-for>.- Index keys on changing lists.
:key="index"mixes up row state when items are inserted or removed; use a stable ID. v-htmlwith user content bypasses escaping and opens an XSS hole; render text with interpolation.
Props, emits and v-model
Section titled “Props, emits and v-model”Props are a component’s inputs, declared with defineProps. With TypeScript, a type argument (defineProps<{ line: OrderLine; currency?: string }>()) gives compile-time checking and IDE help; without it, a runtime object ({ rows: { type: Array, required: true } }) gives development warnings. Since Vue 3.5, destructuring defineProps stays reactive and supports JavaScript default values, as in const { line, currency = 'EUR' } = defineProps(...). Props flow one way: a child must not assign to a prop.
To talk back, a child emits events declared with defineEmits, and the parent listens with @remove="removeLine". For the common “child edits a value the parent owns” case, defineModel() (Vue 3.4 and later) declares a two-way binding: it returns a ref that reads the parent’s value and, when assigned, emits the update for you. The parent binds it with v-model, or v-model:quantity for a named model, and a component can have several. Attributes that are not declared props, such as class or aria-*, fall through to the component’s root element.
<script setup lang="ts">import { computed } from 'vue'
interface OrderLine { sku: string; name: string; unitPrice: number; quantity: number }
const { line, currency = 'EUR' } = defineProps<{ line: OrderLine; currency?: string }>()const quantity = defineModel<number>('quantity', { required: true }) // two-way binding (Vue 3.4+)const emit = defineEmits<{ remove: [sku: string] }>()
const total = computed(() => (line.unitPrice * quantity.value).toFixed(2))</script>
<template> <li class="line" :class="{ bulk: quantity >= 10 }"> <span>{{ line.name }}</span> <input v-model.number="quantity" type="number" min="1" :aria-label="`Quantity of ${line.name}`" /> <strong>{{ total }} {{ currency }}</strong> <button type="button" @click="emit('remove', line.sku)">Remove</button> </li></template><script setup>import { computed, ref } from 'vue'import OrderLineItem from './OrderLineItem.vue'
const lines = ref([ { sku: 'SKU-RED-01', name: 'Red mug', unitPrice: 19.99, quantity: 2 }, { sku: 'SKU-BLU-07', name: 'Blue coaster', unitPrice: 5.5, quantity: 4 },])const itemCount = computed(() => lines.value.reduce((sum, l) => sum + l.quantity, 0))
function removeLine(sku) { lines.value = lines.value.filter((l) => l.sku !== sku)}</script>
<template> <ul> <OrderLineItem v-for="line in lines" :key="line.sku" :line="line" v-model:quantity="line.quantity" @remove="removeLine" /> </ul> <p>{{ lines.length }} lines, {{ itemCount }} items</p></template>// main.js - mounts OrderLines in a jsdom document, edits a quantity and removes a line.import { createApp, nextTick } from 'vue'import OrderLines from './OrderLines.vue'
createApp(OrderLines).mount('#app')const report = () => console.log([...document.querySelectorAll('li')].map((li) => `${li.querySelector('span').textContent}: ${li.querySelector('strong').textContent}${li.classList.contains('bulk') ? ' (bulk)' : ''}`).join(' | '), '->', document.querySelector('p').textContent)report()const input = document.querySelector('input')input.value = '10'input.dispatchEvent(new Event('input')) // what typing doesawait nextTick()report()document.querySelectorAll('button')[1].click() // remove the coaster lineawait nextTick()report()Output:
Red mug: 39.98 EUR | Blue coaster: 22.00 EUR -> 2 lines, 6 itemsRed mug: 199.90 EUR (bulk) | Blue coaster: 22.00 EUR -> 2 lines, 14 itemsRed mug: 199.90 EUR (bulk) -> 1 lines, 10 itemsTyping 10 into the first quantity updated the parent’s lines through v-model:quantity, which recalculated the line total, the bulk class and the parent’s item count; the Remove button emitted remove and the parent filtered its list.
Pitfalls:
- Mutating props. Assigning to a prop or to a property of an object prop makes data flow hard to follow; emit an event or use
defineModelinstead. - Passing a destructured prop to a watcher.
watch(currency, ...)on a destructured prop does not track it; wrap it in a getter:watch(() => currency, ...). - Undeclared emits. Without
defineEmits, a native-looking event such asclickalso falls through to the root element and can fire twice.
Slots let a parent pass template content into a child. The child marks where content goes with <slot>; anything inside the <slot> tag is fallback content shown when the parent provides nothing. A component can have several named slots (<slot name="title">), which the parent fills with <template #title>. A scoped slot passes data back to the parent’s slot content: the child writes <slot name="row" :row="row"> and the parent receives it with <template #row="{ row }">. This is how generic components such as tables, lists and dialogs stay reusable: they own structure and behavior, while each screen decides how a row looks.
<script setup>defineProps({ rows: { type: Array, required: true }, rowKey: { type: String, default: 'id' },})</script>
<template> <section class="table-card"> <header><slot name="title">Results</slot></header> <ul v-if="rows.length"> <li v-for="row in rows" :key="row[rowKey]"> <slot name="row" :row="row">{{ row[rowKey] }}</slot> </li> </ul> <p v-else><slot name="empty">Nothing to show.</slot></p> </section></template><script setup>import DataTable from './DataTable.vue'
defineProps({ orders: { type: Array, required: true } })</script>
<template> <DataTable :rows="orders"> <template #title><h2>Open orders</h2></template> <template #row="{ row }"> <a :href="`/orders/${row.id}`">Order {{ row.id }}</a> for {{ row.customer }} </template> <template #empty>No open orders. Nice work.</template> </DataTable></template>// main.js - renders the screen with two orders, then with none.import { createApp } from 'vue'import OpenOrders from './OpenOrders.vue'
for (const orders of [[{ id: 1001, customer: 'Ada Lopez' }, { id: 1002, customer: 'Ben Ortiz' }], []]) { const el = document.createElement('div') createApp(OpenOrders, { orders }).mount(el) console.log(el.innerHTML)}Output:
<section class="table-card"><header><h2>Open orders</h2></header><ul><li><a href="/orders/1001">Order 1001</a> for Ada Lopez</li><li><a href="/orders/1002">Order 1002</a> for Ben Ortiz</li></ul></section><section class="table-card"><header><h2>Open orders</h2></header><p>No open orders. Nice work.</p></section>Pitfalls:
- Expecting parent scope to see child data. Slot content is compiled in the parent; child values reach it only through scoped slot props.
- A boolean prop for every variation. If a component keeps growing flags such as
showHeaderorcompactRows, a slot is usually the better API. - Mixing
v-sloton the component and named templates. When you use named slots, put the default content in<template #default>as well.
Choosing between them
Section titled “Choosing between them”| Need | Use |
|---|---|
| Parent configures a value the child only reads | Prop |
| Child tells the parent something happened | Emitted event |
| Child edits a value the parent owns | defineModel and v-model |
| Parent decides what markup appears inside the child | Slot |
| Parent’s markup needs the child’s data | Scoped slot |
| Many distant components need the same value | provide/inject or a Pinia store, see Reactivity and state |
Interview questions
Section titled “Interview questions”What does <script setup> change compared with a plain setup() function?
It is compile-time sugar: top-level bindings are exposed to the template automatically, defineProps, defineEmits and defineModel are compiler macros that need no import, and the template is inlined into the same scope, which is both shorter and faster.
What is the difference between v-if and v-show?
v-if adds and removes the element and its component instances, so it is cheaper when the condition rarely becomes true. v-show always renders and toggles display, which is cheaper for frequent toggling.
How does defineModel work under the hood?
It declares a modelValue prop (or a named prop such as quantity) and a matching update:modelValue event, and returns a ref whose getter reads the prop and whose setter emits the event. The parent’s v-model binds both.
Why do scoped slots exist when props already pass data? Props pass data from parent to child. Scoped slots invert that for presentation: the child owns the data and iteration (rows of a table), and the parent controls how each piece renders, without the child knowing about the parent’s markup.
Senior scenario: three teams each built their own order table component with slightly different features. How would you consolidate them?
Design one DataTable that owns structure and behavior (sorting, selection, pagination, empty and loading states) and exposes scoped slots for cells, row actions and the empty state, so each team keeps its own presentation. Put shared state logic in a composable for teams that need custom layouts, publish it with typed props and slot types, and migrate one screen at a time behind visual regression tests.
Related pages
Section titled “Related pages”- Vue overview for versions and the reading path.
- Reactivity and state for
ref,computed, watchers, composables and Pinia. - React components, JSX, props and state for the same ideas in React.