Vue First SFC Page
Creating your first Single File Component
🎯 What is a Vue SFC?
A Single File Component (SFC) combines template, script, and style in one .vue file. It's Vue's way of organizing component code cleanly, making development easier and more maintainable for beginners and experts alike.
<!-- MyFirstComponent.vue -->
<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 Vue!')
function changeMessage() {
message.value = 'You clicked the button!'
}
</script>
<style scoped>
.greeting {
text-align: center;
padding: 20px;
}
</style>
Output:
Hello Vue!
SFC Structure
Template
HTML structure of your component
<template>
<div>Content here</div>
</template>
Script
JavaScript logic and data
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
Style
CSS styling for component
<style scoped>
div {
color: blue;
}
</style>
Scoped
Styles only affect this component
<style scoped>
/* Only applies here */
</style>
🔹 Basic Counter Component
A simple counter to understand SFC basics:
<template>
<div class="counter">
<h2>Count: {{ count }}</h2>
<button @click="count++">Increment</button>
<button @click="count--">Decrement</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<style scoped>
.counter {
padding: 20px;
text-align: center;
}
button {
margin: 5px;
padding: 10px 20px;
}
</style>
Output:
Count: 0
🔹 Using Reactive Data
Vue's ref() makes data reactive:
<template>
<div>
<input v-model="name" placeholder="Enter your name">
<p>Hello, {{ name || 'Guest' }}!</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const name = ref('')
</script>
Output:
Hello, Guest!
🔹 Component Methods
Add functions to handle user interactions:
<template>
<div>
<p>{{ greeting }}</p>
<button @click="sayHello">Say Hello</button>
<button @click="sayGoodbye">Say Goodbye</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const greeting = ref('Welcome!')
function sayHello() {
greeting.value = 'Hello there! 👋'
}
function sayGoodbye() {
greeting.value = 'Goodbye! 👋'
}
</script>
Output:
Welcome!