Vue SFCs & script setup
In a real Vue project, every component lives in its own Single-File Component (SFC): a .vue file with up to three blocks — the template, the script and the styles. A build tool (Vite with @vitejs/plugin-vue) compiles these files into plain JavaScript. Together with the <script setup> syntax, SFCs are the standard way to write Vue 3 apps.
Note: SFCs need a build step, so they can't run in the playgrounds on this page. The
.vuecode below is for reading; each one is followed by a runnable equivalent written withsetup().
Anatomy of an SFC
<!-- src/components/LikeButton.vue -->
<script setup>
import { ref, computed } from 'vue'
const props = defineProps({ initial: { type: Number, default: 0 } })
const emit = defineEmits(['liked'])
const likes = ref(props.initial)
const label = computed(() => (likes.value === 1 ? 'like' : 'likes'))
function like() {
likes.value++
emit('liked', likes.value)
}
</script>
<template>
<button class="like" @click="like">❤️ {{ likes }} {{ label }}</button>
</template>
<style scoped>
.like { border: none; background: #fee2e2; padding: 6px 12px; border-radius: 999px; }
</style>| Block | Purpose |
|---|---|
<script setup> |
Component logic. Top-level bindings are usable in the template automatically |
<template> |
The markup, compiled ahead of time into a render function |
<style scoped> |
CSS that only applies to this component's elements |
What <script setup> does for you
Compared with a hand-written setup():
- No
export default, nosetup()function, noreturn— every top-level variable, function and import is available in the template. - Imported components can be used directly:
import TodoItem from './TodoItem.vue'then<TodoItem />. Nocomponentsoption. - Compiler macros (no import needed):
defineProps,defineEmits,defineModel,defineExpose,defineOptions,defineSlots. - Less code at runtime and better TypeScript inference.
Here is the LikeButton above as a runnable setup() component. Compare them line by line:
<style>
.like { border: none; background: #fee2e2; padding: 6px 12px; border-radius: 999px; margin: 4px; cursor: pointer; }
</style>
<div id="app">
<like-button :initial="0" @liked="onLiked"></like-button>
<like-button :initial="41" @liked="onLiked"></like-button>
<p>Last event: {{ last }}</p>
</div>
<script type="module">
import { createApp, ref, computed } from 'vue';
const LikeButton = {
props: { initial: { type: Number, default: 0 } }, // = defineProps
emits: ['liked'], // = defineEmits
setup(props, { emit }) {
const likes = ref(props.initial);
const label = computed(() => (likes.value === 1 ? 'like' : 'likes'));
function like() {
likes.value++;
emit('liked', likes.value);
}
return { likes, label, like }; // <script setup> makes this automatic
},
template: `<button class="like" @click="like">❤️ {{ likes }} {{ label }}</button>`
};
createApp({
components: { LikeButton },
setup() {
const last = ref('none');
const onLiked = (n) => { last.value = `liked, now ${n}`; };
return { last, onLiked };
}
}).mount('#app');
</script>Compiler macros
| Macro | Replaces | Example |
|---|---|---|
defineProps() |
props option |
const props = defineProps(['title']) |
defineEmits() |
emits option |
const emit = defineEmits(['close']) |
defineModel() |
modelValue prop + update:modelValue emit |
const model = defineModel() |
defineExpose() |
expose() in setup context |
defineExpose({ reset }) |
defineOptions() |
Other options | defineOptions({ inheritAttrs: false }) |
defineSlots() |
Slot types (TypeScript) | defineSlots<{ default(p: { item: T }): any }>() |
Since Vue 3.5, destructured props stay reactive and can have defaults: const { count = 0 } = defineProps(['count']).
Scoped styles
<style scoped> adds a unique attribute such as data-v-7ba5bd90 to every element of the component and rewrites the CSS selectors to match it. Styles can't leak out to other components. The playground simulates what the compiler generates:
<style>
/* what <style scoped> .title { color: … } compiles to */
.title[data-v-a1] { color: #42b883; font-weight: bold; }
.title[data-v-b2] { color: #3b82f6; font-style: italic; }
</style>
<div id="app">
<card-a></card-a>
<card-b></card-b>
<p class="title">An unscoped .title outside both components — unstyled.</p>
</div>
<script type="module">
import { createApp } from 'vue';
const app = createApp({});
app.component('card-a', { template: `<p class="title" data-v-a1>Card A's title</p>` });
app.component('card-b', { template: `<p class="title" data-v-b2>Card B's title</p>` });
app.mount('#app');
</script>Other style options: <style module> (CSS Modules, exposed as $style), :deep(.child) to style inside child components, and v-bind() in CSS to use component state: color: v-bind(themeColor);.
A typical Vite project structure
my-vue-app/
├── index.html
├── vite.config.js plugins: [vue()]
└── src/
├── main.js createApp(App).use(router).use(pinia).mount('#app')
├── App.vue root component with <RouterView />
├── assets/ images, global CSS
├── components/ reusable components (BaseButton.vue, TodoItem.vue)
├── composables/ useSomething.js
├── views/ route-level pages (HomeView.vue, AboutView.vue)
├── router/index.js createRouter(...)
└── stores/ Pinia stores (cart.js)main.js is tiny:
import { createApp } from 'vue'
import App from './App.vue'
import './assets/main.css'
createApp(App).mount('#app')Tip: Install the official Vue - Official extension (formerly Volar) for VS Code. It provides syntax highlighting, autocompletion and type checking inside
.vuefiles.
Test yourself
In <script setup>, how do you make a variable available to the template?
- Return it from
setup() - Declare it at the top level of the script
- Add it to
data() - Export it
Which macro declares the props of a <script setup> component?
useProps()props()defineProps()import { props } from 'vue'
How does <style scoped> keep styles local to a component?
- It uses Shadow DOM
- It adds a unique data attribute to elements and selectors
- It inlines all styles
- It renames every class randomly at runtime