Single-file components

Beginner · 10 min

The anatomy of a .vue file, why Vue colocates template, logic, and styles, how the SFC compiler turns it into JavaScript, and how scoped styles work.

Before thisSetting up a Vue project

Alexander Lichter · 10 min

Single-file components

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Alexander LichterReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A single-file component is a `.vue` file holding one component's `<template>`, `<script>` (usually `<script setup>`), and `<style>` blocks together, so everything about that piece of UI lives in one place.
  • Browsers can't run `.vue` files; `@vitejs/plugin-vue` uses `@vue/compiler-sfc` at build time to compile the template into a render function, turn the script into a JavaScript module, and extract the CSS.
  • Compiling templates ahead of time means the shipped app doesn't need Vue's template compiler, and the compiler can mark static parts of the template so the runtime skips them on updates.
  • `<style scoped>` adds a unique `data-v-*` attribute to the component's elements and rewrites its selectors to match, so the styles only reach that component's own markup and its child components' root elements.
  • Blocks accept a `lang` attribute, such as `<script setup lang="ts">` or `<style lang="scss">`, and the modern convention puts `<script setup>` first, then `<template>`, then `<style>`.

One component, one file

A component has three parts: the markup it renders, the state and behaviour behind that markup, and the styles that make it look right. Those three change together. Rename a field and you touch the template that shows it and the code that sets it; add a “sale” badge and you touch markup and CSS at the same time.

If those parts live in components.html, app.js, and styles.css, every change becomes a three-file scavenger hunt. A single-file component (SFC) puts them side by side in one .vue file:

<script setup>
import { ref } from "vue";

const props = defineProps({ name: String, price: Number });
const inCart = ref(false);
</script>

<template>
  <article class="card">
    <h3 class="title">{{ props.name }}</h3>
    <p>{{ props.price }} EUR</p>
    <button @click="inCart = !inCart">
      {{ inCart ? "Remove" : "Add to cart" }}
    </button>
  </article>
</template>

<style scoped>
.card {
  border: 1px solid #ddd;
  padding: 1rem;
}
.title {
  margin: 0;
}
</style>

That file is the whole ProductCard component. Another component uses it by importing it, import ProductCard from "@/components/ProductCard.vue", and writing <ProductCard name="Mug" :price="12" /> in its template. Props and events between components are their own lessons, starting with components and props; here the focus is the file format itself.

The blocks

An SFC is made of top-level blocks:

  • <template>: at most one. The markup, written in Vue’s template syntax, which the templates and directives group covers in depth.
  • <script setup>: at most one. The component’s logic, written with the Composition API. Every top-level variable, function, and import is automatically available in the template. Its rules get their own lesson in script setup and compiler macros.
  • <script>: at most one plain script. In the Options API style it holds export default { ... }; alongside <script setup> it is only needed for rare cases such as named module exports.
  • <style>: any number. Can be scoped, module, or global.

Vue doesn’t care about block order. The convention changed over time, though. Options API code from the Vue 2 era usually put <template> first. With <script setup>, the script declares the state the template uses, so most current code, and this roadmap, puts <script setup> first, <template> second, and <style> last: definitions before the markup that reads them.

Each block can declare a language with lang:

<script setup lang="ts">
const props = defineProps<{ name: string; price: number }>();
</script>

<style scoped lang="scss">
.card {
  .title { font-weight: 600; }
}
</style>

lang="ts" hands the script to TypeScript (covered in TypeScript with Vue); lang="scss" runs the styles through Sass, provided the sass package is installed.

What the compiler does with it

No browser understands a .vue file. In a Vite project, @vitejs/plugin-vue intercepts every .vue import and runs it through @vue/compiler-sfc, which:

  1. Splits the file into its blocks.
  2. Compiles the script into a standard ES module exporting the component definition. With <script setup>, this is also where the compile-time macros like defineProps are processed.
  3. Compiles the template into a render function, plain JavaScript that produces virtual DOM nodes, and attaches it to the component.
  4. Processes the styles: runs preprocessors, applies scoped rewriting, and hands the CSS to Vite.

You can watch this happen in the Vue SFC Playground: type a component on the left, then open the “JS” and “CSS” tabs to see the compiled output.

Compiling at build time has two payoffs. Your production bundle can use Vue’s runtime-only build, which leaves out the template compiler entirely and is noticeably smaller. And the compiler can see the whole template, so it marks parts that can never change, like a static heading, and tells the runtime which dynamic bindings to check. React’s JSX is also compiled, but into plain function calls; Vue’s template compiler goes further and annotates which nodes are static and which bindings are dynamic. Performance optimization in Vue returns to what the compiler buys you.

Scoped styles

Global CSS in a component-heavy app runs into the classic problem: a .title rule written for one card restyles every .title on the site. Naming conventions like BEM are one answer, described in CSS architecture and naming conventions. <style scoped> is Vue’s built-in one.

When a style block is scoped, the compiler gives the component a unique id and does two things. It adds a data-v-<id> attribute to every element in that component’s template, and it rewrites every selector to require that attribute:

<!-- rendered output -->
<article class="card" data-v-7ba5bd90>
  <h3 class="title" data-v-7ba5bd90>Mug</h3>
</article>
/* compiled CSS */
.card[data-v-7ba5bd90] { border: 1px solid #ddd; padding: 1rem; }
.title[data-v-7ba5bd90] { margin: 0; }

No JavaScript runs at runtime; it is plain attribute selectors. Two details matter in practice:

  • A child component’s root element gets both attributes, the parent’s and its own, so the parent can position or size a child from its own scoped styles. Elements deeper inside the child don’t get the parent’s attribute.
  • :deep() reaches further on purpose. Writing .card :deep(.title) in the parent compiles to .card[data-v-7ba5bd90] .title, which matches any .title inside the card, including inside child components. Use it sparingly, typically to style a third-party component.

CSS Modules (<style module>), binding CSS values to component state with v-bind() inside <style>, and the wider styling choices are covered in styling Vue components.

When one file gets too big

A common objection: doesn’t putting HTML, JS, and CSS in one file break separation of concerns? It changes which concerns are separated. Splitting by file type separates technologies; splitting by component separates features, and features are what change together. When a single .vue file grows past a few hundred lines, that is a signal to extract a child component or move logic into a composable, not a signal to split the file by language. The general idea behind this is covered in component-based architecture.

What the video covers

Alexander Lichter, a Nuxt core team member, uses the question of block order to walk through what an SFC is and why it’s useful. He covers the benefits of SFCs, the older template-first order, the modern script-first order, why the change came with the Composition API, and how it looks on real components. The video doesn’t cover the compiler or scoped styles; the sections above do. The freeCodeCamp chapter in the links below covers component basics and the separation-of-concerns argument for beginners, and LearnVue’s short video covers scoped styles.

Check yourself

  1. 01What happens to a .vue file between saving it and the browser running it?

    Vite passes it to `@vitejs/plugin-vue`, which uses `@vue/compiler-sfc` to split the file into its blocks. The script becomes a normal JavaScript (or TypeScript, then JavaScript) module, the template is compiled into a render function attached to that component, and the styles are processed (scoped rewriting, preprocessors) and handed to Vite's CSS pipeline. The browser only ever receives JavaScript and CSS.

  2. 02Isn't putting HTML, JavaScript, and CSS in one file a violation of separation of concerns?

    It separates by a different axis. Splitting by file type puts the markup, behaviour, and styling of one feature in three distant places, even though they change together. An SFC separates by feature: each component is its own concern, with its three parts colocated. You can still split a large component into smaller components, or move logic into composables, when one file grows too big.

  3. 03A parent component has `<style scoped>` with `.title { color: red }`. Will it colour an element with class `title` deep inside a child component's template?

    No. Scoped selectors are rewritten to require the parent's `data-v-*` attribute, which only the parent's own elements and each child component's root element receive. Elements inside the child's template carry only the child's attribute. To reach into a child deliberately, the parent would use the `:deep(.title)` selector.

  4. 04Why does the community now tend to put `<script setup>` before `<template>`?

    With the Composition API the script defines the state and functions the template uses, so reading top to bottom you see the definitions before the markup that references them. The template-first order was the convention in the Options API era; both are valid, and Vue doesn't care about block order.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark