0
0
Vueframework~5 mins

Single File Components concept in Vue

Choose your learning style9 modes available
Introduction

Single File Components let you keep your HTML, JavaScript, and CSS for a Vue component all in one file. This makes your code neat and easy to manage.

When building a Vue app and you want to organize each component's code in one place.
When you want to reuse a component with its own style and behavior easily.
When working in a team so everyone can understand and update components quickly.
When you want to separate your app into small, manageable pieces.
When you want to use Vue's tooling that supports these files for better development experience.
Syntax
Vue
<template>
  <!-- HTML goes here -->
</template>

<script setup>
// JavaScript goes here
</script>

<style scoped>
/* CSS goes here */
</style>

The <template> block holds the HTML structure.

The <script setup> block contains the JavaScript logic using Vue's Composition API.

Examples
A simple button component that counts clicks. The style applies only to this component.
Vue
<template>
  <button @click="count++">Clicked {{ count }} times</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>

<style scoped>
button {
  font-size: 1.2rem;
  padding: 0.5rem 1rem;
}
</style>
A heading component showing a title with scoped styling.
Vue
<template>
  <h1>{{ title }}</h1>
</template>

<script setup>
const title = 'Hello Vue Single File Component'
</script>

<style scoped>
h1 {
  color: teal;
}
</style>
Sample Program

This component lets the user type their name. It updates the greeting below as they type. The input has an accessible label, and styles apply only inside this component.

Vue
<template>
  <div>
    <input v-model="name" placeholder="Enter your name" aria-label="Name input" />
    <p>Hello, {{ name || 'stranger' }}!</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const name = ref('')
</script>

<style scoped>
div {
  max-width: 300px;
  margin: 1rem auto;
  font-family: Arial, sans-serif;
}
input {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
}
p {
  margin-top: 0.5rem;
  font-size: 1.2rem;
  color: #333;
}
</style>
OutputSuccess
Important Notes

Use scoped on the style tag to keep CSS inside the component only.

The <script setup> syntax is simpler and recommended for Vue 3.2+.

Single File Components work best with build tools like Vite or Vue CLI.

Summary

Single File Components keep HTML, JS, and CSS together for easier coding.

They help organize your app into small, reusable parts.

Scoped styles prevent your CSS from affecting other parts of the app.