This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

What is a scoped

On the style tag in the Vue file, there is a special attribute: scoped. When a style tag has the scoped attribute, its CSS style applies only to the current component; that is, the style applies only to the current component element. With this property, you can enable the interaction between components

The patterns do not pollute each other. If all style tags in a project are scoped, the style is modularized.

Advantages: className is never the same and automatically generates HTML with hash Attitude, such as:

<div class="test">hi</div> 

.test { color: red; } 
Copy the code
<div class="test" data-v-df38f3e>hi</div> .test[data-v-df38f3e] {color: red; }Copy the code

Data-v-xxx generation is generated based on relative path + content

How do I modify child component styles in parent components

When a label has scoped, its CSS only applies to the elements in the current component, and the parent component’s style will not permeate the child component. Suppose I have a scenario where I use a component library, but the component library component has a default style. I want the style to suit my needs. How do I change it?

  1. Use under Stylus >>>
<style scoped> 
  .a >>> .b {
    color: red;
  }
</style>
Copy the code

The above code will compile to.a[data-v-xxx].b

2. Use /deep/ for sass and less

.el-contain-row /deep/ .el-table__header-wrapper {
    height: 20px;
}
Copy the code

There are two ways to write deep ::v-deep is the most compatible

  1. ClassPrefix prefix

    This is equivalent to dynamically passing class to child components, such as:

    In the child component

<div :class="{selected: type==='apple', 
[classPrefix+'-item']:classPrefix}" 
@click="selectType('apple')">   Apple </div>
Copy the code

In the parent component

<template>
   <Layout>
       <Child :type.sync="yyy" class-prefix="xxx"/>
   </Layout>
</template>
<style lang="scss" scoped>
    ::v-deep .xxx-item{
        border: 1px solid black;
    } 
</style> 
Copy the code

Matters needing attention

1. Multiple >>>, /deep/ or ::v-deep operators, only the outermost layer is valid, subsequent operators are not processed.

El-select. el-input does not support SASS preprocessors, and the >>> operator has browser compatibility problems

El-select. el-input Does not support SASS preprocessors. :deep(. El-select. el-input) supports SASS preprocessors

4. In Vue 3, >>> and /deep/ are not supported. It is recommended to use ::v-deep and ::v-deep(.class) writing rules

5. Two new operators, :: V-slotted and :: V-global, are also available in Vue 3 for

and global CSS rules. The :: V-slotted attribute is data-v-xxx-s, and the suffix -s makes it specific to

content

6. ::v-global is compiled without data-v-xxx attributes