从事Vue开发好几年一直都在使用深度选择器,但从来没有深究为什么要这么使用,产生的根本原因是什么?
1.深度选择器是什么?
了解深度选择器前我们需要晓得选择器是什么?
CSS 选择器 是用来给
HTML元素
添加样式的。常用的选择器:
- 标签选择器:
p
选择所有的<p>
元素。- 类选择器:
.my-class
选择所有具有class="my-class"
的元素。- ID选择器:
#my-id
选择具有id="my-id"
的元素。- 更多选择器
深度选择器 是为了解决样式作用域问题而出现的特殊选择器。
样式作用域
<style scoped>
在Vue等框架 中,为了保持组件的样式独立(不污染全局样式),我们通常使用样式作用域CSS。
根本原因:组件化开发
在Vue、React等框架中,组件是独立的:
html
<!-- 父组件 Parent.vue -->
<style scoped>
/* 这个样式只作用于父组件 */
.parent-content {
font-size: 16px;
}
/* 这个选择器无法选中子组件内部的元素! */
.child-button {
background: red; /* ❌ 不会生效 */
}
</style>
<template>
<div class="parent-content">
<ChildComponent />
</div>
</template>
html
<!-- 子组件 ChildComponent.vue -->
<template>
<div class="child">
<button class="child-button">子组件按钮</button>
</div>
</template>
<style scoped>
/* 子组件有自己的样式作用域 */
.child-button {
background: blue;
}
</style>
编译后:
html
<!-- 编译后的HTML -->
<div class="parent-content" data-v-parent-123>
父组件内容
<div class="child" data-v-child-456>
<button class="child-button" data-v-child-456>
子组件按钮
</button>
</div>
</div>
css
/* 编译后的CSS */
.parent-content[data-v-parent-123] { font-size: 16px; }
/* 父组件想选择子组件按钮,但选择器不匹配 */
.child-button[data-v-parent-123] {
background: red; /* ❌ 无法匹配 */
}
.child-button[data-v-child-456] {
background: blue; /* ✅ 正常生效 */
}
深度选择器:解决作用域穿透
css
/* 深度选择器让父组件样式穿透到子组件 */
.parent-content ::v-deep .child-button {
background: red; /* ✅ 现在会生效了 */
}
编译后:
css
.parent-content[data-v-parent-123] .child-button {
background: red; /* ✅ 成功匹配 */
}
穿透前: 穿透后:
2.深度选择器有哪些?
Vue2深度选择器:::v-deep
、/deep/
、>>>
>>>
: 主要用于原生CSS样式穿透/deep/
: 在CSS预处理器中可能存在问题(已弃用)::v-deep
: vue 2.5以后推荐用法
Vue3深度选择器::deep()
css
<style scoped>
.a :deep(.b) {
/* ... */
}
</style>