DEV Community

Cover image for Vue Academy #1: Scoped style
Code Oz
Code Oz

Posted on • Updated on

Vue Academy #1: Scoped style

Welcome to the first vue academy ! It will be a list of lot of article on vue! I have 2.5 years of experience in this and I can teach a few thing about this !

For this course we will focus on scoped attribute in CSS.

A quick example :

<style>
    .toto {
        color: blue;
    }
</style>

<template>
    <div class='toto'> Hi </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Why it's bad

It will work but your class can be used in any other component. So if you change toto class, it can impact other component style (side effect).

If you want to declare general class, you should create a properly file for this.

Solution

The solution to create a class that can be used by only one component is the attribute scoped in <style>.

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

CSS will be applied to the elements of the current component only. This is similar to the style encapsulation found in Shadow DOM.

How it's work in deep

When you will compile your code, the code above will be equal to

<style>
    .toto[data-v-f3f3eg9] {
        color: blue;
    }
</style>

<template>
    <div class='toto' data-v-f3f3eg9> Hi </div>
</template>
Enter fullscreen mode Exit fullscreen mode

As you can see it's very simple & basic but very strong. Vue will inject an attribute on the scoped class and apply this attribute on each element that include the scoped class !.


I hope you like this reading!

🎁 You can get my new book Underrated skills in javascript, make the difference for FREE if you follow me on Twitter and MP me 😁

Or get it HERE

🎁 MY NEWSLETTER

☕️ You can SUPPORT MY WORKS 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : https://twitter.com/code__oz

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!

Top comments (1)

Collapse
 
ippatev profile image
Aleksandr Ippatev

okay