preface

  • 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.

  • 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"> ScopedCopy the code

After the translation:

.example[data-v-5558831a] { color: red; } <template> <div class="example" data-V-5558831A > Scoped </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).

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 penetration using >>> Outer >>> third party component styles.wrapper >>>. Swiper-pagination-bullet-active background: # FFF sass and less style penetrates using /deep/ outer /deep/ third-party components {style}.wrapper /deep/. Swiper-pagination-bullet-active {background: # FFF; }Copy the code

Summary: Scoped rendering rules:

Add a non-repeating data attribute to the HTML DOM node (for example: Data-v-5558831a) to uniquely identify the DOM element. At the end of each CSS selector (the compiled CSS statement), add a data attribute selector for the current component (e.g. [data-V-5558831A]) to privatise the style

To make vUE page styles modular and not globally polluting, it is recommended that the style tag on each page be scoped to indicate that the style belongs only to the current page and that the parent component’s style does not leak into the child component.

<style scoped>

</style>
Copy the code

But scoped also imposes some additional burdens, such as not being able to override the style of the original component. You can add /deep/. Depth effect selector /deep/ or >>> If you want the selector in scoped style to “go deep”, that is, affect the child components

Example:

/deep/ .el-table .red-row {

background: #ffc2c2;

}

or


.el-table >>> .red-row {

background: #ffc2c2;

}


Copy the code

Sass /less may not recognize >>>, so use the /deep/ selector.