Skip to the workspace
Pebellslearn by building
Components  ›  Lesson

Single File Components

Single File Components 13 minA .vue file keeps one component's logic, template and styles together in script setup, template and style blocks.

vue / Single File Components

Explore each scene at your own pace.

01 · The rule

The rule

Single File Components

Shelf will show a card for every book: title, page count and a button to mark it read. In plain web code that card would be spread across an HTML file, a JavaScript file and a CSS file, and you would hunt through all three to change it. Vue puts one component in one file.

The rule

One .vue file, three blocks: logic, markup, styles.

A single file component, or SFC, is a file ending in .vue. Here is Shelf's first card, src/components/BookCard.vue:

<script setup>
import { ref } from 'vue'

const title = 'Dune'
const read = ref(false)

function toggle() {
  read.value = !read.value
}
</script>

<template>
  <article class="card">
    <h3>{{ title }}</h3>
    <button @click="toggle">{{ read ? 'Finished' : 'Reading' }}</button>
  </article>
</template>

<style scoped>
.card { border: 1px solid #ccc; padding: 1rem; }
</style>
  • <script setup> holds the logic. Every variable, function and import at its top level is automatically usable in the template. No export or return is needed.
  • <template> holds the markup. {{ title }} prints a value; @click listens for a click. A ref such as read is written plainly here, while script code reads and writes read.value.
  • <style scoped> holds CSS. The word scoped makes Vue stamp this component's elements with a unique attribute, so .card here cannot restyle a .card in another component.

ref(false) makes a reactive value: when it changes, Vue re-renders the parts of the template that use it. You will study ref properly in the API Styles section; for now, know that changing read.value updates the button text.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.