Hello, everyone, MY name is Xiao Zhu, this article I want to share a content is “several solutions to resolve style conflicts in Vue”

Ask questions

We all know that Vue is a framework for component-based development, which makes us more efficient, so there is a style conflict problem.

The solution

  • Scoped CSS
  • CSS Modules

Scoped CSS

<style scoped>
.color {
  color: red;
}
</style>
Copy the code

To do so, simply add the scoped property to the style tag, where the style only takes effect within that component.

The principle of analytic

So let’s write this code

<template>
  <div>
    <h2 class="color">hello world</h2>
  </div>
</template>
​
<style scoped>
.color {
  color: red;
}
</style>
Copy the code

The results

We can see that all the element nodes of this component have a data-V-09260093 property added, and the corresponding CSS has added a property selector for this class. The selected property is data-V-09260093. So the idea behind scoped is to add custom attributes to an element, and CSS adds corresponding attribute selectors.

CSS Modules

<template>
  <div>
    <h1 :class="$style.color">hello world</h1>
  </div>
</template>
<style module>
.color {
  color: red;
}
</style>
Copy the code

$style = ‘this.$style’; $style = ‘this.$style’

The principle of analytic

Its implementation principle is also relatively simple, generating a special CSS class name.

conclusion

These are two solutions to CSS conflicts, and there are many more. Thanks for reading.