DEV Community

Cover image for Single File Components in Two Minutes
Gabe
Gabe

Posted on • Edited on

6 2

Single File Components in Two Minutes

Single-File-Components or SFC is a Vue.js feature that allows us to build our entire component - template, logic, and styles, in one .vue file.

Below is an example of a component that displays a paragraph element with static text and a dynamic winner.

<template>
<p>And the winner is: {{ winner }}</p>
</template>

<script>
module.exports = {
    data: function () {
        return {
            winner: 'You'
        }
    }
}
</script>


<style scoped>
p {
    color: blue;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Template & Script

The template portion of this example is a paragraph element with some template syntax that allows us to render data to the DOM.

Templates in single-file components must be wrapped in one HTML tag, so if we wanted to include multiple paragraph elements in our example, we would have to wrap our elements in a div or a similar container element.

In between the script tags are where our logic and data are found. The data and DOM are linked allowing us to dynamically change our data, so if we were to change the winner data to say 'me', the DOM would reflect that change reactively.

Style

<style scoped>
p {
    color: blue;
}
</style>
Enter fullscreen mode Exit fullscreen mode

In the example above, the style tag features the attribute scoped. This attribute allows us to style the elements of the current component only.

Meaning if this component is featured on a page with other paragraph elements, only the paragraph element in this component will take on the color blue, the rest will follow whatever default rules were set for the paragraph elements.




For additional reading on single file components or the Vue framework in general, I recommend checking out the official Vue.js documentation

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay