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
.vuefile, 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;@clicklistens for a click. A ref such asreadis written plainly here, while script code reads and writesread.value.<style scoped>holds CSS. The wordscopedmakes Vue stamp this component's elements with a unique attribute, so.cardhere cannot restyle a.cardin 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.
The shortcut
Read any SFC by asking three questions in order: what does it know (script), what does it show (template), how does it look (style).
What does it know?
In the script: a fixed
title, a reactivereadflag starting atfalse, and atogglefunction that flips it.
A frequent slip is writing read = true in the script. read is the ref box itself, and the value inside lives in .value. The template unwraps it for you; the script does not.
Drills
Answer fast — trust the rule.
In BookCard.vue, where does the toggle function live?
What does scoped on the style block do?
Inside <script setup>, how do you set the ref read to true?
Which variables in <script setup> can the template use?
Remember
- An SFC is one
.vuefile with<script setup>,<template>and<style>blocks. - Shortcut: read it as knows, shows, looks.
- Trap: forgetting
.valueon a ref in script code; the template unwraps it, the script does not.
