vue 中父级样式深度覆盖子组件

发布时间:2021-04-01 10:30:40编辑:admin阅读(2792)

    一、概述

    项目需要的原因,在sub组件的父级list组件中需要用到xhcj组件,同时sub组件中也用到了xhcj组件,两个地方代码逻辑是相同,仅仅是样式有些微的差别,所以决定共用组件,然后覆盖样式。

    style标签上的scoped属性会致使样式只作用于当前组件,对子组件是不起作用的,但是不加scoped会使父级引入的xhcj和这里引用的xhcj样式都变化,所以也是不可以的。

    二、解决方法

    这是最开始写的版本,在sub中,我写了两个style标签,需要覆盖的那部分没有加scoped属性,也实现了我需要的效果,但是写两个style标签还是觉得不太合适。

    <style scoped>
       ...
    </style>
    <style>
    //.subscribe  这个样式sub组件中的,是为了覆盖这个组件下面的xhcj组件的样式  
      .subscribe .xhjj{
        border: none;
        position: static;
        background: transparent;
        width: auto;
        height: auto;
        .sbottom{
          height: auto;
          overflow: inherit;
          overflow-x: inherit;
          .treeFirst{
            border: none;
            background: transparent;
          }
          .flex-w-wrap{
            background-color: transparent!important;
            .treethird{
              width: 25%;
            }
          }
        }
      }
    
    </style>

     

     然后改成了下面这个版本

    <style scoped>
      ...... 
      .subscribe /deep/ .xhjj{
        border: none;
        position: static;
        background: transparent;
        width: auto;
        height: auto;
        .sbottom{
          height: auto;
          overflow: inherit;
          overflow-x: inherit;
          .treeFirst{
            border: none;
            background: transparent;
          }
          .flex-w-wrap{
            background-color: transparent!important;
            .treethird{
              width: 25%;
            }
          }
        }
      }
    
    </style>

     

    重点位置已经标红,这里有了scoped属性,不再使用两个style标签去写。

    但是使用/deep/可以深度选择到子组件,也就不限于样式只对当前组件有效了。

    /deep/可以用>>>进行替代,但是>>>这个某些预编译器可能无法正常解析,所以可以使用/deep/进行代替,作用是一样。

     

    本文参考链接:

    https://blog.csdn.net/qq_40851816/article/details/95213145


关键字