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 Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay