vue项目正确使用样式deep穿透

经常开发前端的程序员应该都知道前端一般都是组件化开发,为了避免样式污染通常会使用scoped添加属性选择器,此时如果我们想在父组件中修改子组件的样式便成了难题。其实,我们可以通过以下几种方式修改子组件样式,

  • 组件样式穿透

我们可以直接在父组件调用子组件时给组件添加样式,此方案只能添加子组件最外一层样式,如下

<!--子组件-->
<templete>
<div class="child-test1">
  <div class="child-test2"></div>
</div>
</templete>
<script lang="ts" setup>
defineOptions({
  name:"childComponent"
})
</script>
<style scoped lang="scss">
.child-test1{
  width:100px;height:100px;background:red;
  .child-test2{
    width:50px;height:50px;background:green;
  }
}
</style>
<!--父组件-->
<templete>
<div class="father-test1">
  <test class="father-test2"></test>
</div>
</templete>
<script lang="ts" setup>
import test from 'test.vue'
defineOptions({
  name:"FatherComponent"
})
</script>
<style scoped lang="scss">
.father-test1{
  width:200px;height:200px;
  .father-test2{
    background:yellow;
  }
}
</style>
  • deep样式穿透

通过deep穿透样式,我们可以更改子组件内部任意样式,如下

<!--父组件-->
<templete>
<div class="father-test1">
  <test></test>
</div>
<!--错误示例->
<!--<div>
  <test  class="father-test1"></test>
</div>-->
</templete>
<script lang="ts" setup>
import test from 'test.vue'
defineOptions({
  name:"FatherComponent"
})
</script>
<style scoped lang="scss">
:deep(.father-test1){
  width:200px;height:200px;
  .child-test2{
    background:yellow;
  }
}
</style>

注意,使用deep的演示类不能挂载在组件上,否则不生效