Vue Single-File Components (SFCs)
Vue's Single-File Components (SFCs) bundle a component's template, logic, and styles into one `.vue` file. A build tool compiles this into browser-readable JS and CSS, turning your template into optimized render functions.
WHY IT EXISTS: Before SFCs, a single component's concerns—its HTML structure, its JavaScript logic, and its CSS styles—were often split across multiple files. This made components harder to manage and reason about. SFCs were created to co-locate all related code for a component into one cohesive file.
THE MENTAL MODEL: A Vue Single-File Component is a custom file format (.vue) that acts as a self-contained blueprint for a piece of your UI. It bundles the three core aspects of a component—structure (<template>), logic (<script>), and presentation (<style>)—into one organized file. Think of it as a complete recipe card for an interface element.
HOW IT WORKS: A .vue file is not understood by browsers. It requires a build tool like Vite or Vue CLI, which uses @vue/compiler-dom to parse the file. The compiler processes each language block separately. The <template> block is pre-compiled into highly efficient JavaScript render functions. The <script> block is treated as an ES Module that exports the component's definition. The <style> block is processed into CSS, which can be automatically scoped to the component to prevent styles from leaking.
WHEN TO USE IT: SFCs are the standard and recommended way to write components in any Vue project that has a build step. They are ideal for creating reusable, maintainable, and well-organized UI elements. You can enhance blocks with pre-processors by adding a lang attribute, for example, <script lang="ts"> for TypeScript or <style lang="scss"> for Sass.
WHEN NOT TO USE IT: Avoid SFCs if you are using Vue without a build step, such as including it from a CDN with a single <script> tag. In that scenario, you define components as plain JavaScript objects. SFCs are specifically designed for a development environment with a compilation pipeline.
ONE CANONICAL EXAMPLE: A file named UserProfile.vue contains a <template> with the user's profile markup, a <script setup> block to fetch user data, and a <style scoped> block to style the profile card. The build tool compiles this into a single JavaScript module. Because the filename is UserProfile.vue, you can recursively reference it within its own template as <UserProfile /> if needed.
Read the original → vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.