从事Vue开发之查漏补缺:深度选择器

从事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>
相关推荐
菜泡泡@17 小时前
仓库地图vue-grid-layout
前端·javascript·vue.js
2013编程爱好者21 小时前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
change_fate1 天前
el-menu折叠后文字下移
前端·javascript·vue.js
天外天-亮1 天前
Vue + excel下载 + 水印
前端·vue.js·excel
0***K8921 天前
Vue数据挖掘开发
前端·javascript·vue.js
t***26591 天前
SpringBoot + vue 管理系统
vue.js·spring boot·后端
蓝胖子的多啦A梦1 天前
ElementUI表格错位修复技巧
前端·css·vue.js·el-table表格错位
H***99761 天前
Vue深度学习实战
前端·javascript·vue.js
code_Bo1 天前
Ant Design Vue 日期选择器英文不变更中文问题
前端·vue.js·ant design
U***e631 天前
Vue自然语言
前端·javascript·vue.js