Scoped implementation principles and style penetration methods and principles in Vue

1. What is scoped and why should we use it?

On the style tag in the vue file, there is a special attribute: scoped.

When a style tag has a scoped attribute, its CSS style can only be applied to the current component. Through this attribute, the styles between components can be prevented from contaminating each other.

2. The principle of scoped

Generate a unique identifier for the component instance, add a label attribute to the DOM element corresponding to each label in the component, and
use data-v-xxxx to

3. Example

Vue code before translation
<template>
	<div class="example">hello world</div>
</template>

<style scoped>
.example {
	color: red;
}
</style>
After translation:
<template>
	<div class="example" data-v-49729759>hello world</div>
</template>

<style scoped>
.example[data-v-49729759] {
	color: red;
}
</style>

4. Why do we need to penetrate scoped?

After referencing a third-party component, you need to locally modify the style of the third-party component in the component without removing the scoped attribute and causing style contamination between components. At this time, scoped can only be penetrated through special methods.

5. Methods of style penetration

There are three ways to write style penetration: >>>, /deep/, ::v-deep

>>>

If the project uses CSS native styles, you can directly use >>> penetrating modification

/*  用法:  */
div >>> .cla {
	color: red;
}
/deep/

The preprocessor scss, sass, and less operator >>> are used in the project, and an error may be reported because it cannot be compiled. You can use /deep/
. Note: vue-cli3 or above is not available.

/*  用法:  */
div /deep/ .cla {
	color: red;
}
::v-deep
/*  用法:  */
div ::v-deep .cla {
	color: red;
}

6. Principle of style penetration

The selector after scoped will add a logo of the current component by default. For example,
after using style penetration in [data-v-49729759], the selector after deep will not add a logo at the end.

Example

Parent component:

<template>
  <div class="cssdeep">
    <!-- 样式穿透 -->
    <cssdeepcom></cssdeepcom>
  </div>
</template>

<script>
import cssdeepcom from '../components/cssdeepcom'
export default {
  data(){
    return{

    }
  },
  components:{
    cssdeepcom,
  },
}
</script>

<style lang="less" scoped>
.cssdeep /deep/ .cssdeepcom{
  background: blue;
}
</style>

Subassembly:

<template>
  <div class="cssdeepcom"></div>
</template>

<script>
export default {
  data(){
    return{

    }
  },
}
</script>

<style lang="less" scoped>
.cssdeepcom{
  width: 100px;
  height: 100px;
  background: red;
}
</style>

After the parent component uses penetration, the identifier [data-v-xxxx] is not followed by cssdeepcom. Instead, the identifier of the parent component is followed at the end of the upper level of deep.

Guess you like

Origin blog.csdn.net/shanghai597/article/details/131912390