The role and principle of the style tag attribute scoped

In the vue project, the scoped attribute is often added to the style tag at the bottom of the page, and we will introduce the understanding of this scoped attribute.

1. Function

When there is a scoped attribute in the style tag, its css only acts on the elements in the current component. In a single-page project, the components can not pollute each other and achieve modularity.

2. Principle

By using postCss to realize the conversion, add a dynamic attribute to the dom, and then add the corresponding attribute to the css attribute to select the dom, so that the style only acts on the dom that contains the attribute, and the modularization of the component style is realized.

Before conversion:

<templete>
	<div class='test'>hillo!</div>
</templete>
<style scoped>
	.test{
    
    color:red;}
</style>

After conversion:

<templete>
	<div class='test' data-v-4f795181>hillo!</div>
</templete>
<style scoped>
	.test[data-v-4f795181]{
    
    color:red;}
</style>

The converted code can be viewed through the browser's console inspection element.

3. How to modify the style with scoped attribute

Our projects often use third-party component libraries, such as ElementUI; its styles all use scoped attributes. If we need to change the ElementUI style of some pages, we need to penetrate scoped, generally use the depth selector /deep/ or'>>>' to penetrate the attributes.

Modify the third-party plug-in style:

<style scoped>
	.test /deep/ .el-menu-item {
    
     color:red; }
</style>
//或者
<style scoped>
	.test >>> .el-menu-item {
    
     color:red; }
</style>

If /deep/ reports an error or does not take effect, use ::v-deep

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/112978697