How do you organize CSS isolation in Vue components in your projects?
sobes.tech AI
Answer from AI
CSS in Vue components can be isolated in several ways:
-
Scoped CSS: Using the
scopedattribute in the<style>tag of the component.<style scoped> .my-component { /* Styles apply only to elements in this component */ color: blue; } </style>Vue adds unique attributes to elements and corresponding CSS rules to ensure isolation.
-
CSS Modules: Using the
moduleattribute in the<style>tag.<style module> .myClass { color: green; } </style> <template> <div :class="$style.myClass"> Hello </div> </template>This creates a locally hashed class accessible via the
$styleobject in the template and script, avoiding naming conflicts. -
CSS-in-JS libraries (e.g., Styled Components, Emotion): Integrating third-party libraries to write styles directly in JavaScript.
import styled from 'vue-styled-components'; const MyComponent = styled.div` color: purple; `; export default { components: { MyComponent } // ... }These libraries generate unique classes and inject styles into the document head, ensuring isolation.
The choice of method depends on the project requirements and team preferences. Scoped CSS is the simplest for small projects, CSS Modules are convenient for larger codebases requiring explicit style management, and CSS-in-JS offers full integration of styles and logic in JavaScript.