vue3 css deep 不生效,scoped和deep原理

1、scoped原理

scoped 会在元素上添加唯一的属性(data-v-xxxx),css编译后也会加上属性选择器,从而达到限制作用域的目的。

使用 scoped 后,父组件的样式将不会渗透到子组件中。不过,子组件的根节点会同时被父组件的作用域样式和子组件的作用域样式影响。这样设计是为了让父组件可以从布局的角度出发,调整其子组件根元素的样式。

2、deep原理

3、vue3中失效

在 vue3 中用:deep(),需要 vue3 的template里加上父标签,并在 less 中使用父标签包裹 要穿透的样式内容

<template>
    <div class="test">
        <h1>这是父组件</h1>
        <HelloWorld />
    </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src

@Options({
    components: {
        HelloWorld
    }
})
export default class HomeView extends Vue {}
</script>
<style scoped lang="less">
.test {
    background: pink;
}
.child {
    :deep(.boxes) {
        background: black;
    }
    :deep(.wrapper) {
        .box-child {
            background: orange;
        }
    }
}
</style>
<template>
    <div class="child">
        <h1 class="box">这是子组件box</h1>
        <h1 class="test">这是子组件test</h1>
        <h1 class="hello">这是子组件hello</h1>
        <h3 class="boxes">111</h3>
        <div class="wrapper">
            <h3 class="box-child">222</h3>
        </div>
    </div>
</template>

<style scoped lang="less">
.test {
    background: yellow;
}
.hello {
    background: green;
}
.box {
    background: blue;
}
.boxes {
    background: yellow;
}
.box-child {
    background: yellow;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值