1. What is scoped

There is a special attribute, scoped, on the style tag in the Vue file. When a style tag has the scoped attribute, its CSS styles can only be applied to the current Vue component, so that the styles of the components do not pollute each other. If all style tags in a project are scoped, you are modularizing the style.Copy the code

2. Implementation principle of Scoped

The effect of the Scoped attribute in Vue is mainly implemented via PostCss. Here is the code before translation:

<style scoped lang="less">
    .example{
        color:red;
    }
</style>
<template>
    <div class="example">Scoped test cases</div>
</template>
Copy the code

After the translation:

<style lang="less">
    .example[data-v-5558831a] {
    color: red;
    }
</style>
<template>
    <div class="example" data-v-5558831a>Scoped test cases</div>
</template>
Copy the code

PostCSS adds a unique dynamic property to all of the DOM in a component, and adds a corresponding property selector to the CSS selector to select the DOM in the component, so that the style only applies to the DOM element containing the property (the DOM inside the component).

Summary: Scoped rendering rules:

1. Add a unique data attribute (such as DATA-V-5558831A) to the HTML DOM node to uniquely identify the DOM element; 2. Add a data property selector for the current component (e.g. [data-V-5558831A]) to the end of each CSS selector (the compiled CSS statement) to privatise the style;Copy the code

3. The scoped to penetrate

Scoped seems to work well. In the Vue project, when we introduced a third-party component library (such as vue-awesome-swiper for mobile rotation), we needed to modify the style of the third-party component library in a local component without removing the scoped property and causing style overwriting between components. At this point we can penetrate scoped in a special way.

  • Stylus style penetrates use>>>
Outer >>> Third-party component styles.wrapper >>> .swiper-pagination-bullet-active
background: #fff
Copy the code
  • Sass and less style penetration are used/deep/
The outer /deep/ Third-party components {styles}.wrapper /deep/ .swiper-pagination-bullet-active{
      background: #fff;
    }
Copy the code

4. Other ways to modify third-party component library styles in components

Above we showed you how to modify the styles of imported third-party component libraries by scopd penetration when using the Scoped property. Now we show you other ways to modify the styles of imported third-party component libraries

  1. The scoped attribute is not used in the VUE component;
  2. Use two style tags in the Vue component, one with the scoped attribute and one without the scoped attribute. Write the CSS style to be covered in the style tag without the scoped attribute.
  3. Create a reset.css(base Global Styles) file that contains the overridden CSS styles and import them in the entry file main.js;

Reference links: segmentfault.com/a/119000001…