🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 避免CSS全局污染 1. **scoped 属性** 2. **css in js** ```CSS const styles = { bar: { backgroundColor: '#000' } } const example = (props)=>{ <div style={styles.bar} /> } ``` 3. **使用less**,尽量少使用全局对选择器 ```CSS // 选择器上>要记得写,免得污染所有ul下面的li ul{ >li{ color:red; } } ``` 4. **CSS Modules** https://www.ruanyifeng.com/blog/2016/06/css_modules.html CSS Modules是构建步骤中的一个进程。通过构建工具使指定class达到scope的过程。 CSS Modules允许使用:`:global(.className)`的语法,声明一个全局规则。 凡是这样声明的`class`,都不会被编译成**哈希字符串**。 `:local(className)`: 做 localIdentName 规则处理,编译唯一哈希类名。 CSS Modules使用特点: 不使用选择器,只使用 class 名来定义样式 不层叠多个 class,只使用一个 class 把所有样式定义好 不嵌套class ```js // webpack.config.js -> module.rules { test: /\.scss$/, use: [ 'vue-style-loader', { loader: 'css-loader', options: { modules: true } }, 'sass-loader' ] } ``` 在`<style>`上添加 module 后,一个叫做 $style 的计算属性就会被自动注入组件 Vue 3.x 中的 **useCSSModule** ```vue <template><span :class="$style.span1">hello 333 - {{ text }}</span></template> <script> import { useCSSModule } from '@vue/composition-api'; export default { props: { text: { type: String, default: '' } }, setup(props, context) { const $style = useCSSModule(); return { $style }; } }; </script> <style lang="scss" module> .span1 { color: green; font-size: 30px; } </style> ``` 在 .vue 文件中可以定义不止一个 `<style module>` ## **css穿透** 场景:修改引入的第三方组件的CSS样式 在style经常用scoped属性实现组件的私有化,所以才需要样式穿透 1. `>>>` 只作用于css 2. `::v-deep` 只作用于sass 3. `/deep/` 只作用于less ```css <style scoped> 外层 >>> 第三方组件类名 { 样式 } </style> ``` ## **scoped的原理** vue中的scoped 通过在DOM结构以及css样式上加唯一不重复的标记:data-v-hash的方式,以保证唯一(PostCSS转译实现的),达到样式私有化模块化的目的。 ```html <style lang="scss" scoped> .test { background: blue; span{ color:red; } } </style> <template> <div class="test"><span>hello world !</span> </div> </template> // 转译后 <style lang="css"> .test[data-v-ff86ae42] { background: blue; } .test span[data-v-ff86ae42]{ color: red; } </style> <template> <div class="test" data-v-ff86ae42><span data-v-ff86ae42>hello world !</span> </div> </template> ``` PostCSS会给一个组件中的所有dom添加了一个独一无二的动态属性data-v-xxxx,然后,给CSS选择器额外添加一个对应的属性选择器来选择该组件中dom,这种做法使得样式只作用于含有该属性的dom——组件内部dom, 从而达到了'样式模块化'的效果.