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.
Every .vue file is naturally divided into three distinct sections.
<template>: This block contains all of your HTML markup.<script>: This block contains your JavaScript logic and Vue instance data.<style>: This block contains your CSS styling.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> 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> 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!
Let's look at a fully constructed Single File Component.
<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>
Which three main HTML tags are used to divide the code within a Vue Single File Component (.vue)?