首页 > 解决方案 > 来自子组件的 Vue 3 插槽样式

问题描述

摘要:我需要<slot>从子组件中对 a 的内容进行样式设置。我正在使用作用域 css 并且样式不适用:

我有以下两个组件:

<!-- Parent.vue -->
<template>
  <h1>{{ msg }} from Parent</h1>
  <Child>
    <h1>{{ msg }} from Child</h1>
  </Child>
</template>
...
<style scoped>
h1 {
  color: green;
}
</style>

<!-- Child.vue -->
<template>
  <slot></slot>
</template>
...
<style scoped>
h1 {
  color: red;
}
</style>

我希望第二个<h1>是红色的,但它是绿色的,因为组件是用类似的东西渲染的:

<h1 data-v-452d6c4c data-v-2dcc19c8-s>Hello from Child</h1>

<style>
h1[data-v-452d6c4c] {
  color: green;
}
h1[data-v-2dcc19c8] {
  color: red;
}
</style>

data-v-452d6c4c来自父母,data-v-2dcc19c8-s来自孩子

如果标签中的第二个属性<h1>只是data-v-2dcc19c8我想要的样式,那么它将被应用,但由于它具有该-s后缀(插槽?),它不会。

我可能会找到一些其他的解决方案,但我很少使用<slot>,我想了解内部工作原理。这-s告诉我,我正在尝试做的事情可以在框架的帮助下处理,我错过了什么?

工作样本:

https://codesandbox.io/s/condescending-brown-ilfwn

标签: cssvue.jsvue-componentvuejs3vue-slot

解决方案


使用Vue 3 中的新:slotted选择器:

孩子.vue

<template>
  <slot></slot>
</template>

<script>
export default {
  name: "Child",
};
</script>

<style scoped>
:slotted(h1) {
  color: red !important;
}
</style>

在 Vue 3 中,scoped默认情况下子样式不会影响插槽内容。

在这种情况下,!important修饰符是必要的,因为父级还定义了一个h1样式,否则将优先


推荐阅读