iview - css >>> 、 /deep/ 进行样式穿透
前言
在使用vue构建项目的时候,引用了第三方组件库,只需要在当前页面修改第三方组件库的样式以做到不污染全局样式。通过在样式标签上使用scoped达到样式只制作用到本页面,但是此时再修改组件样式不起作用。
scoped的实现原理
vue中的scoped属性的效果主要通过PostCSS转译实现,如下是转译
前的vue代码:
前的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; } }
————————————————
原文链接:https://blog.csdn.net/idomyway/article/details/94659598