用深度选择器>>> ( /deep/ )解决vue调用第三方组件库覆盖样式不生效问题 短命女 2022-12-16 06:22 109阅读 0赞 ### 前言 ### 在使用vue构建项目的时候,引用了第三方组件库,只需要在当前页面修改第三方组件库的样式以做到不污染全局样式。通过在样式标签上使用`scoped`达到样式只制作用到本页面,但是此时再修改组件样式不起作用。 ### scoped的实现原理 ### vue中的scoped属性的效果主要通过`PostCSS`转译实现,如下是转译 前的vue代码: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> 转译后: <style> .example[data-v-5558831a] { color: red; } </style> <template> <div class="example" data-v-5558831a>hi</div> </template> ### 通过 `>>>` 穿透scoped ### iview中需要`在组件上使用i-class声明第三方组件类名` <style scoped> 外层 >>> 第三方组件类名{ 样式 } </style> 有些Sass 、Less之类的预处理器无法正确解析 >>>。可以使用 /deep/操作符( >>> 的别名) <style lang="sass" scoped> /deep/ 第三方组件类名 { 样式 } </style> ### 实例 ### <template> <input i-class="ivu-input"> </template> // 样式 .num-input { width: 90px; margin-top: 15px; >>> .ivu-input { text-align: center!important; } } // Less || Sass .num-input { width: 90px; margin-top: 15px; /deep/ .ivu-input { text-align: center!important; } } **注意**: 穿透方法实际上违反了`scoped`属性的意义。而且在vue中过多使用scoped导致页面打包文件体积增大。通常能写在index中的样式尽量写在index中,我们可以通过在index样式中通过外层组件添加`唯一class`来区分组件+`第三方样式`来实现实现了类似于scoped的效果,又方便修改各种第三方组件的样式。 // index.less .num-input { width: 90px; margin-top: 15px; .ivu-input { text-align: center!important; } } 小伙伴们今天的学习就到这里了,如果觉得本文对你有帮助的话,欢迎转发,评论,收藏,点赞!!! 每天学习进步一点点,就是领先的开始。如果想继续提高,欢迎关注我,或者关注公众号”祯民讲前端“。大量前端技术文章,面试资料,技巧等助你更进一步! ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhb2ZhbmRlZGFpbWE_size_16_color_FFFFFF_t_70_pic_center] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhb2ZhbmRlZGFpbWE_size_16_color_FFFFFF_t_70_pic_center]: /images/20221123/acfab8a915074e05b145fd22decf6f52.png
还没有评论,来说两句吧...