4

Vue Academy #1: Scoped style

 3 years ago
source link: https://dev.to/codeozz/vue-academy-1-scoped-style-5g0e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for Vue Academy #1: Scoped style

Vue Academy #1: Scoped style

Jul 3

・1 min read

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 modeExit 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 modeExit 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 modeExit 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 !.

Hi I'm Code-Oz

Thank you for reading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK