一直以为在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>