Vue SFC

Vue Single File Components (SFC)

When using a build tool like Vite, you unlock the ability to write Single File Components.

A Single File Component (SFC) is a file with a .vue extension.

It allows you to encapsulate the template, logic, and styling of a Vue component all within a single file.


The Structure of an SFC

Every .vue file is naturally divided into three distinct sections.

  1. <template>: This block contains all of your HTML markup.
  2. <script>: This block contains your JavaScript logic and Vue instance data.
  3. <style>: This block contains your CSS styling.

The Template Block

The <template> tag is where you write your standard HTML.

You can freely use all of the Vue directives we learned previously, like v-if and v-for.

This section defines exactly what the user will see on their screen.


The Script Block

The <script> tag is where your reactive state, methods, and lifecycle hooks live.

In modern Vue 3, we often use <script setup> which heavily simplifies the code syntax.

It automatically exposes variables and functions directly to the template without needing a return statement.


The Style Block

The <style> tag holds the CSS rules for your component.

By default, these styles are global and apply to the whole website.

However, adding the scoped attribute ensures the CSS only affects that specific component!


A Complete SFC Example

Let's look at a fully constructed Single File Component.

HelloWorld.vue Example:

<template>
  <div class="greeting">
    <h1>{{ message }}</h1>
    <button @click="changeMessage">Click Me</button>
  </div>
</template>

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

const message = ref('Hello from a Single File Component!')

function changeMessage() { message.value = 'The message was changed!' } </script>

<style scoped> .greeting { padding: 20px; background-color: #f4f4f4; border-radius: 8px; } h1 { color: #42b883; } </style>


Exercise 1 of 1

?

Which three main HTML tags are used to divide the code within a Vue Single File Component (.vue)?