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

Myth丶恋晨 2022-11-13 09:26 387阅读 0赞

一、概述

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

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

二、解决方法

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

  1. <style scoped lang='scss'>
  2. ...
  3. </style>
  4. <style lang="scss">
  5. //.subscribe 这个样式sub组件中的,是为了覆盖这个组件下面的xhcj组件的样式
  6. .subscribe .xhjj{
  7. border: none;
  8. position: static;
  9. background: transparent;
  10. width: auto;
  11. height: auto;
  12. .sbottom{
  13. height: auto;
  14. overflow: inherit;
  15. overflow-x: inherit;
  16. .treeFirst{
  17. border: none;
  18. background: transparent;
  19. }
  20. .flex-w-wrap{
  21. background-color: transparent!important;
  22. .treethird{
  23. width: 25%;
  24. }
  25. }
  26. }
  27. }
  28. </style>

然后改成了下面这个版本

  1. <style scoped lang="scss">
  2. ......
  3. .subscribe /deep/ .xhjj{
  4. border: none;
  5. position: static;
  6. background: transparent;
  7. width: auto;
  8. height: auto;
  9. .sbottom{
  10. height: auto;
  11. overflow: inherit;
  12. overflow-x: inherit;
  13. .treeFirst{
  14. border: none;
  15. background: transparent;
  16. }
  17. .flex-w-wrap{
  18. background-color: transparent!important;
  19. .treethird{
  20. width: 25%;
  21. }
  22. }
  23. }
  24. }
  25. </style>

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

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

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

本文参考链接:

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

发表评论

表情:
评论列表 (有 0 条评论,387人围观)

还没有评论,来说两句吧...

相关阅读