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>