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.
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:
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:
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.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Differentiate Client and Server Components
Nuxt allows you to define client-side and standalone server components
Vue Tip: Emit Event From Composable
Your application may contain a lot of components that are using the same logic, like emitting the same event. In this case, it might be tempting to create a composable that will emit this event and is used in all components. But how do you emit an event from inside a composable?