DEV Community

Cover image for Single File Components in Two Minutes
Gabe
Gabe

Posted on • Updated on

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

Top comments (0)