Vue Single-File Components (SFCs)
Vue Single-File Components (.vue files) colocate a component's template, logic, and styling into one modular unit. This is the standard for building Vue SPAs and static sites, enabling scoped CSS and pre-compiled templates. Remember, SFCs require a build step.
WHY IT EXISTS Building complex UIs with separate HTML, CSS, and JS files often scatters the code for a single component across the codebase. A component's template, logic, and style are inherently coupled. SFCs were created to group these coupled concerns together in a single file, improving modularity and maintainability.
THE MENTAL MODEL Think of a .vue file as a self-contained, portable component blueprint. It encapsulates everything needed to render, style, and manage the state of one piece of the UI. This colocation makes components easier to reason about, share, and refactor, as all its constituent parts are in one place.
HOW IT WORKS A .vue file is a special format with three main blocks: <template> for HTML structure, <script> for JavaScript logic, and <style> for CSS. These files are not directly understood by browsers. A build tool like Vite or Vue CLI uses the @vue/compiler-sfc package to parse the .vue file and compile it into a standard JavaScript ES module and CSS. The JS module can then be imported and used like any other in your application. During development, styles are injected for hot reloading, while in production, they are extracted into a single, optimized CSS file.
WHEN TO USE IT SFCs are the defining feature of Vue and the recommended approach for most projects. Use them for Single-Page Applications (SPAs), Static Site Generation (SSG), or any complex frontend where a better development experience and compile-time optimizations are valuable. The benefits include pre-compiled templates, component-scoped CSS, and better IDE support with auto-completion.
WHEN NOT TO USE IT If you are only adding light interactions to an existing static HTML page, a full build setup for SFCs can be overkill. In these scenarios, using Vue via a simple script tag is more appropriate, as it avoids the need for a build step. For these use cases, Vue offers lighter options like petite-vue.
ONE CANONICAL EXAMPLE A simple SFC for a greeting component would have a <template> block containing a paragraph like {{ greeting }}. A <script> block would export a default object with a data function returning { greeting: 'Hello World!' }. Finally, a <style> block could add styling, like making the paragraph's color red. All three blocks live together in a single Greeting.vue file.
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.