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?
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With