Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use "scoped" styles in VueJS single file components?

The docs on VueJS state that scoped should limit styles to the component. But if I create 2 components with same baz style, it will leak from one component into another:

foo.vue

<template>   <div class="baz">     <Bar></Bar>   </div> </template>  <style scoped> .baz {   color: red; } </style> 

bar.vue

<template>   <div class="baz">bar</div> </template>  <style scoped> .baz {   background-color: blue; } </style> 

I expect that baz will be different in both components. But after generating a web page, I can see the red text on blue background, which means that foo's scoped style affects the bar component. The generated code looks like this:

<div class="baz" data-v-ca22f368>   <div class="baz" data-v-a0c7f1ce data-v-ca22f368>     bar   </div> </div> 

As you can see, the "leak" is intentionally generated by VueJS via specifying two data attributes into the bar component. But why?

like image 643
grigoryvp Avatar asked Aug 26 '17 19:08

grigoryvp


People also ask

What is scoped style in Vue?

With scoped , the parent component's styles will not leak into child components. However, a child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. This is by design so that the parent can style the child root element for layout purposes.

Should always be multi word Vue multi word component?

Component names should always be multi-word, except for root App components, and built-in components provided by Vue, such as <transition> or <component> . This prevents conflicts with existing and future HTML elements, since all HTML elements are a single word.

How do I use style CSS in Vue?

In Vue. js, we can add an inline style to our element by binding the style attribute in the HTML tag. For reference, :style is shorthand for v-bind:style . Inline styling can be done in two ways: using object syntax or array syntax.


1 Answers

You can read on the Vue loader's docs:

A child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS.

This is apparently what it is meant to do, even though it might seem a bit confusing.

If you want to avoid that, you should use css modules:

<template> <div :class="$style.baz">   <Bar></Bar> </div> </template>  <style module> .baz {   color: red; } </style> 
like image 90
Mario Lamacchia Avatar answered Oct 12 '22 13:10

Mario Lamacchia