scoped property

scopedIt is a Vue component option, which is used to limit the scope of CSS styles and prevent the pollution of global styles. When a component's scopedproperty is set to true, the component's style will only be applied to the elements inside the component, and will not affect the styles of other components or pages.

For example, in a Vue single-file component, if <style>the tag is added with scopedthe attribute, the style of the component will only affect the elements inside the component, and will not affect the styles of other components or pages. The advantage of this is that the problems of style conflict and style coverage can be avoided, and the reusability and maintainability of components are improved.

In fact, scoped cannot refer to global styles

If we want to refer to the global style under the scoped attribute

Global styles can be used inside scoped styles using :globalthe directive. For example, use the :global directive inside a scoped style to use the global style:

<template>
  <el-button class="my-button">My Button</el-button>
</template>

<style scoped>
.my-button {
  color: red;
  font-size: 16px;
  /* 使用 :global 指令来使用全局样式 */
  border: 1px solid :global(--my-border-color);
}
</style>

If you want to make a selector in a scoped style work "deeper", such as affecting styles inside subcomponents, you can use the  >>> or /deep/ operator:

For example

<template>
  <div class="parent">
    <h1>Parent Component</h1>
    <div class="child">
      <h2>Child Component</h2>
    </div>
  </div>
</template>

<style scoped>
.parent h1 {
  color: red;
}

.child >>> h2 {
  color: blue;
}
</style>

.parentIs a class in the parent component, .childand is .parentthe class of the child component in . In the scoped style, .parent h1the selector will only affect the tag in the parent component h1, not h2the tag of the child component. In order to select the label in the child component h2, we use the depth selector >>>, which will select h2the label in the child component and set its color to blue. It should be noted that depth selectors only work on the last element of the selector, so in this case it is .childstill limited by the scoped style.

Guess you like

Origin blog.csdn.net/m0_63263973/article/details/129477216