← Back to Vue.js Course | Chapter 10: Best Practices | Lesson 2 of 6

Single file components

A single-file component keeps a component's template, script and style together in one .vue file.

In this page:

  1. Single file components
Syntax
markup
<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

markup
<!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
  1. Trying to load .vue files directly in the browser
  2. Forgetting scoped on styles
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.