Skip to content
☆´∀`☆
On this page

v3.2 巧用单文件组件的 style 特性

深度选择器:deep()

父组件样式覆盖

插槽选择器:slotted()

选择 slot 内的元素

vue
<template>
  <div class="c-container">
    <slot></slot>
  </div>
</template>

<style scoped>
.c-container {
  width: 100px;
  height: 100px;
}
:slotted(.h2) {
  color: red;
}
</style>
vue
<template>
  <div class="home-container">
    <Children>
      <h2 class="h2">H2</h2>
    </Children>
  </div>
</template>

<script setup>
import Children from "@/components/Children.vue";
</script>

<style scoped>
.h2 {
  color: green;
}
</style>

结果为绿色,就近原则。

全局选择器:global()

vue
<style scoped>
:global(.red) {
  color: red;
}
</style>

结果为 .red { color: red; }

style module

vue
<template>
  <h1 :class="$style.red">Hi</h1>
</template>

<script setup></script>

<style module>
.red {
  color: red;
}
</style>
vue
<template>
  <h1 :class="$style[colorName]">Hi</h1>
</template>

<script setup>
import { ref } from "vue";

const colorName = ref("red");
</script>

<style module>
.red {
  color: red;
}
</style>
vue
<template>
  <p :class="classes.red">red</p>
</template>

<style module="classes">
.red {
  color: red;
}
</style>

获取 style module

vue
<template>
  <h1 :class="$style[colorName]">Hi</h1>
</template>

<script setup>
import { ref, useCssModule } from "vue";

const colorName = ref("red");
const styleModule = useCssModule();
console.log(styleModule);
</script>

<style module>
.red {
  color: red;
}
</style>

在 style 中使用 v-bind

vue
<template>
  <h1 class="text">Hi</h1>
</template>

<script setup>
import { ref } from "vue";

const color = ref("red");
</script>

<style>
.text {
  color: v-bind(color);
}
</style>