在 Vue 中,scoped 是一个用于 标签的特殊属性,表示样式只作用于当前组件,不会影响到其他组件。它是 Vue 实现组件样式隔离的常用方式。
<template>
<div class="title">Hellodiv>
template>
<style scoped>
.title {
color: red;
}
style>
✅ 上面的 .title 样式只会作用于当前组件里的 .title,而不会影响其他组件中同名类名的元素。
当你在
<div class="title" data-v-123456>Hellodiv>
并将 CSS 编译为:
.title[data-v-123456] {
color: red;
}
这样保证样式只作用于这个组件的 DOM。
如果你希望样式对子组件生效,可以使用 ::v-deep(深度选择器)。
当你想作用于子组件内部的元素(如封装的 UI 组件),需要这样写:
<style scoped>
::v-deep .child-element {
color: blue;
}
style>
Vue 2 使用的是 /deep/ 或 >>>(已弃用)
Vue 3 推荐 ::v-deep
特性 |
|
|
---|---|---|
作用范围 | 当前组件 | 全局 |
冲突风险 | 低 | 高(类名可能冲突) |
推荐场景 | 普通组件样式隔离 | 全局样式、主题、reset.css |
<template>
<div class="msg">Welcomediv>
template>
<script setup>
// setup 逻辑
script>
<style scoped>
.msg {
font-size: 20px;
}
style>
一样生效,不影响作用机制。
• ChildComponent.vue:子组件,内部有一个 .button 元素
• ParentComponent.vue:父组件,想修改子组件中的 .button 样式
<template>
<div class="wrapper">
<button class="button">Click mebutton>
div>
template>
<script setup>
// 子组件逻辑
script>
<style scoped>
.button {
background-color: gray;
color: white;
padding: 8px 16px;
border: none;
}
style>
<template>
<div class="parent">
<ChildComponent />
div>
template>
<script setup>
import ChildComponent from './ChildComponent.vue'
script>
<style scoped>
/* 修改子组件内部 .button 的样式 */
::v-deep(.button) {
background-color: tomato;
font-weight: bold;
}
style>
::v-deep(.button) {
background-color: tomato;
}
.parent ::v-deep(.button) {
color: red;
}
<template>
<div class="wrapper">
<button class="button">Click mebutton>
div>
template>
<script setup>
// 子组件没有 scoped 或 CSS Modules
script>
<style>
.button {
background-color: gray;
color: white;
padding: 8px 16px;
border: none;
}
style>
<template>
<div :class="$style.parent">
<ChildComponent />
div>
template>
<script setup>
import ChildComponent from './ChildComponent.vue'
script>
<style module>
.parent :deep(.button) {
background-color: tomato;
font-weight: bold;
}
style>