Sometimes I see new devs coming to Vue.js getting confused about scoped CSS in Vue.js. Some using it without really knowing how does it work.

If you are there, I hope this tip helps you understand why and when to use them (and when not).

I’m not going to dive deep into the theory as you have it already in the vue-loader docs. Just to know, it’s a vue-loader’s feature to avoid style collisions and encapsulate styles by emulating Shadow DOM functionality.

Let’s better see an example of a problematic situation when you don’t use scoped CSS.

Imagine we have a BaseList.vue component with the following structure:

<template>
  <ul class="list">
    <li class="list-item" v-for="item in items" :key="item">
      {{ item }}
    </li>
  </ul>
</template>

Then create two components with the same code. Call them RedList.vue and BlueList.vue:

<template>
  <BaseList :items="items" />
</template>

<script>
import BaseList from "./BaseList";

export default {
  props: ["items"],
  components: {
    BaseList
  }
};
</script>

#vue #vue.js #css #programming

The importance of scoped CSS in Vue.js
1.45 GEEK