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的演示类不能挂载在组件上,否则不生效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值