vue中使用scoped后,父组件样式仍然覆盖子组件样式解决方案

一直以为在style中加了scoped ,样式就都是相对独立的 

可是,在我将同名的样式名称分别添加给父组件和子组件时,虽然都添加了scoped,但是子组件的样式并没有生效。

父组件 

<template>
  <div class="container">
    <card title="标题" sub-title="哈哈哈"></card>
  </div>
</template>
<script setup lang="ts">
import card from "./card.vue"
</script>
<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  height: calc(100% - 90px);
}
</style>

子组件 

<template>
    <div class="container">
      <div class="title">{{ title }}</div>
      <div v-if="subTitle !== ''" class="sub_title">{{ subTitle }}</div>
    </div>
</template>
<script setup lang="ts">

const props = defineProps({
  title: "",
  subTitle: "",
});
</script>
<style lang="scss" scoped>
.container {
  width: 690px;
  margin: 0 30px 30px;
  padding: 30px;
  background-color: pink;
  border-radius: 10px;
}
.title {
  font-family: Source Han Sans;
  font-size: 32px;
  font-weight: normal;
  line-height: 44px;
  color: #333333;
}
.sub_title {
  font-family: Source Han Sans;
  font-size: 28px;
  font-weight: normal;
  line-height: 31px;
  color: #aa7d45;
  margin-top: 20px;
}
</style>

如图子组件根元素背景色样式未生效,被父元素覆盖了。

只需在子组件添加一个根元素,这样就可以隔离开了。 如图所示,可以看到只有根元素会继承的。

子元素

<template>
  <div>
    <div class="container">
      <div class="title">{{ title }}</div>
      <div v-if="subTitle !== ''" class="sub_title">{{ subTitle }}</div>
    </div>
  </div>
</template>
<script setup lang="ts">

const props = defineProps({
  title: "",
  subTitle: "",
});
</script>
<style lang="scss" scoped>
.container {
  width: 690px;
  margin: 0 30px 30px;
  padding: 30px;
  background-color: pink;
  border-radius: 10px;
}
.title {
  font-family: Source Han Sans;
  font-size: 32px;
  font-weight: normal;
  line-height: 44px;
  color: #333333;
}
.sub_title {
  font-family: Source Han Sans;
  font-size: 28px;
  font-weight: normal;
  line-height: 31px;
  color: #aa7d45;
  margin-top: 20px;
}
</style>

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值