全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-20 5 分钟 ✍️ juanwangdev

组件样式作用域

Vue 提供 scoped 属性实现组件样式隔离。

基本用法

vue
<style scoped>
.title {
  color: red;
}
</style>

编译后:

CSS
.title[data-v-f3f3eg9] {
  color: red;
}

混合使用

vue
<style>
/* 全局样式 */
.global {
  font-size: 16px;
}
</style>

<style scoped>
/* 局部样式 */
.local {
  color: blue;
}
</style>

子组件样式穿透

vue
<style scoped>
/* 深度选择器 */
:deep(.child-class) {
  color: red;
}

/* 旧版写法 */
::v-deep(.child-class) {
  color: red;
}
</style>

动态组件样式

vue
<style scoped>
.is-active {
  background: blue;
}
</style>

<template>
  <div :class="{ 'is-active': isActive }">内容</div>
</template>

使用 scoped 时,子组件的根元素会同时受父组件和子组件样式影响。

要点总结

  • scoped 属性为样式添加数据属性隔离
  • 可混合使用全局和局部样式
  • 使用 :deep() 穿透子组件样式
  • 推荐默认使用 scoped 避免样式污染
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 组件通信
下一篇 → 插槽
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码