Javascript is required
ยท
1 min read

Vue Tip: Split Your SFC into Multiple Files

Vue Tip: Split Your SFC into Multiple Files Image

Vue provides a special file format to combine the template, logic, and styling of a component in a single file. This format is called Single-File Component (SFC) also known as *.vue file.

Component.vue
1<script setup>
2import { ref } from 'vue'
3const count = ref(0)
4</script>
5
6<template>
7  <p class="greeting">{{ count }}</p>
8</template>
9
10<style scoped>
11.counter {
12  color: orangered;
13}
14</style>

This format is very convenient for small components, but it can become a bit overwhelming for larger components. In this case, you can split your SFC into multiple files using the src attribute to import an external file for a language block:

Component.vue
1<script src="./script.js"></script>
2
3<template src="./template.html"></template>
4
5<style scoped src="./styles.css"></style>

Warning

This approach doesn't work with the <script setup> block. Compiler macros like defineProps or defineEmits are compiler macros only usable inside <script setup>.

But you can import any JavaScript/Typescript file:

Component.vue
1<script setup lang="ts">
2defineProps<{ msg: string }>()
3
4import { msg } from './script.ts'
5</script>
6
7<template src="./template.html"></template>
8
9<style scoped src="./styles.css"></style>

Try it yourself:

Info

I personally never needed and used this feature, but I think it's good to know that it exists.

Instead, I prefer to use Composition API to extract shared logic in a separate file or split the component into multiple components.