Vue Application Structure
How a Single-File Component is put together, and what belongs in template, script, and style.
阅读需 2 分钟
Every piece of UI in a Vue application is a component, and the standard way to author one is a Single-File Component (SFC) — a .vue file with up to three blocks.
<script setup>
import { ref } from "vue";
const count = ref(0);
</script>
<template>
<button @click="count++">Clicked {{ count }} times</button>
</template>
<style scoped>
button {
padding: 0.5rem 1rem;
border-radius: 6px;
}
</style>The three blocks
<script setup>holds the component's logic — state, computed values, functions, imports. Anything declared at the top level here (likecount) is automatically available to the template, with no manualreturnorexportneeded.<script setup>is compile-time syntax sugar; a build step transforms it into a normal component definition before your app ships.<template>holds the markup, written as HTML with Vue's template syntax layered on top (covered in the next lesson). A component must have exactly one root structure here, though as of Vue 3 that can be a<template>containing multiple top-level elements — called a fragment — not just a single wrapping<div>.<style scoped>holds CSS. Thescopedattribute is optional but common: Vue rewrites your selectors under the hood so these styles only apply to this component's own template, not globally — you don't have to invent unique class name prefixes to avoid collisions.
Why bundle all three together
Splitting a UI into separate HTML/CSS/JS files made sense when a "component" was really just a page. Once your UI is decomposed into dozens of small, reusable pieces — a button, a card, a modal — colocating a component's markup, logic, and styling in one file keeps everything you need to understand or change it in one place, instead of jumping between three directories to edit one button.
Composing components
A component becomes usable inside another by importing and registering it — <script setup> auto-registers anything you import:
<script setup>
import HelloWorld from "./components/HelloWorld.vue";
</script>
<template>
<main>
<HelloWorld />
</main>
</template>App.vue is just a component like any other; it's simply the one main.js mounts. As your app grows, App.vue typically shrinks down to little more than layout and top-level routing, delegating everything else to child components — a pattern the components lessons later in this course build on directly.