Single-File Components
Single-File Components, aka .vue
files, a specially formatted file that allows for the template, logic, and styling of a Vue component to live all in a single file.
Below is an example of the Single-File Component.
<template>
<p class="greeting">{{ greeting }}</p>
</template>
<script>
export default {
data() {
return {
greeting: 'Hello World!'
}
}
}
</script>
<style>
.greeting {
color: red;
font-weight: bold;
}
</style>
Notice that the Single-File Component divides the template, logic, and styling using three high-level tags: <template>
, <script>
, and <style>
.
Why to Use
Single-File Components may require more initial setup to use, but they come with numerous benefits, including:
- All parts of the component reside in a single file
- Better IDE support with syntax highlighting, auto-completion, and type-checking
- Component-scoped CSS
- Better optimization and performance
How to Use
Single-File Components cannot be directly rendered by the browser and must be pre-compiled into JavaScript and CSS. A compiled Single-File Component is a standard JavaScript module and can be imported using the import
statement.
import MyComponent from './MyComponent.vue'
export default {
components: {
MyComponent
}
}
Typically, the compiling of Single-File Components is performed by build tools such as Vite or Vue CLI.