css - 来自子组件的 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
告诉我,我正在尝试做的事情可以在框架的帮助下处理,我错过了什么?
工作样本:
解决方案
使用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
样式,否则将优先
推荐阅读
- ruby-on-rails - 使用 AWS 签名在 HTTParty 中重新创建邮递员发布请求
- php - 我不能加载多个帖子
- mysql - mysql - 从表中创建摘要父行和子行
- java - 编译失败,JavaScanner.skipBlockComment 上由 scala-maven-plugin 驱动的 Java 1.8 (Scala 2.12.10 = Spark 2.4.6) 出现 StackOverflowError
- python - 在本地加载 Amazon Sagemaker NTM 模型以进行推理
- python - Tensorflow 2 图像批量预测返回结果
- python - 一种在不转换为极坐标或从极坐标转换的情况下旋转矢量的方法
- javascript - 如何使用 Express 将外部 CSS 文件加载到 HTML 中
- python - Python 参数行为
- ios - 为什么 SwiftLint whitelist_rules 不适用于我的项目?