How to use scoped styles in Vue.js single file components?

Sometimes, we want to use scoped styles in Vue.js single file components.

In this article, we’ll look at how to use scoped styles in Vue.js single file components.

How to use scoped styles in Vue.js single file components?

To use scoped styles in Vue.js single file components, we can add the module attribute to the style tag.

For instance, we write

<template>
  <div :class="$style.baz">
    <Bar></Bar>
  </div>
</template>

<style module>
.baz {
  color: green;
}
</style>

to add the style tag with the module attribute so we can use $style to add the styles in the template.

We add the baz class in style and set its color to green.

Then we set the class prop of the div to $style.baz to apply the baz class to the div to make its content color green.

Conclusion

To use scoped styles in Vue.js single file components, we can add the module attribute to the style tag.