Single file components
A single-file component keeps a component's template, script and style together in one .vue file.
In this page:
Syntax
<template>
<!-- markup -->
</template>
<script setup>
import { ref } from 'vue';
const name = ref(value);
</script>
<style scoped>
/* styles */
</style>
Single file components
A .vue file has a template block, a script (often script setup) and an optional scoped style. Build tools like Vite compile them.
Scoped styles apply only to that component. The runnable page below is the same component written without a build step, with the .vue version shown in the comment.
Note:
script setup is the recommended, most concise SFC syntax.
Example: Single file components
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<!--
Counter.vue
<script setup>
import { ref } from "vue";
const count = ref(0);
</script>
<template><button @click="count++">Clicked {{ count }}</button></template>
<style scoped>button { color: teal; }</style>
-->
<div id="app"><counter-button></counter-button></div>
<script>
const app = Vue.createApp({});
app.component("counter-button", {
setup() { const count = Vue.ref(0); return { count }; },
template: '<button @click="count++" style="color:teal">Clicked {{ count }}</button>',
});
app.mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Clicked 0
-->
Related Topics
Common Mistakes
- Trying to load .vue files directly in the browser
- Forgetting scoped on styles
- Placing logic in the template
Chapter Summary
- SFCs combine template, script and style
- Compiled by Vite or webpack
- scoped limits styles
- script setup is concise
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: