【问题标题】:Vue 3 slot styles from child component来自子组件的 Vue 3 插槽样式
【发布时间】:2021-06-06 09:26:09
【问题描述】:

总结:我需要从子组件设置<slot> 的内容样式。我正在使用作用域 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>

我希望第二个&lt;h1&gt; 是红色的,但它是绿色的,因为该组件是用类似的东西呈现的:

<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 来自 Parent,data-v-2dcc19c8-s 来自 Child

如果&lt;h1&gt; 标记中的第二个属性只是data-v-2dcc19c8,我想要的样式将被应用,但由于它有-s 后缀(插槽?),它没有。

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

一个工作样本:

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

【问题讨论】:

    标签: css vue.js vue-component vuejs3 vue-slot


    【解决方案1】:

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

    Child.vue

    <template>
      <slot></slot>
    </template>
    
    <script>
    export default {
      name: "Child",
    };
    </script>
    
    <style scoped>
    ::v-slotted(h1) {
      color: red !important;
    }
    </style>
    

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

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

    【讨论】:

    • 感谢您的回答,我一直在寻找一种在 Vue 中进行开槽样式的方法
    • 文档中是否有关于此的页面?在文档中搜索 v-slotted 未显示任何结果
    猜你喜欢
    • 2021-02-01
    • 2018-04-29
    • 2021-11-16
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2018-09-14
    • 2021-02-06
    相关资源
    最近更新 更多