如何将样式应用于 Svelte 中的插槽元素?
How to apply styles to slot element in Svelte?
我希望将在一个模块中声明的样式应用到该模块的插槽元素(在另一个文件中填充)。
这是以下示例的 Svelte REPL:
App.html
<List>
{{#each items as item}}
<li><a>{{item}}</a></li>
{{/each}}
</List>
<script>
import List from './List.html'
export default {
components: {
List
}
}
</script>
List.html:
<h1>A Special List</h1>
<ul>
<li><a>Let's all be red!</a></li>
<slot></slot>
</ul>
<style>
ul a {
color: red;
}
</style>
数据:
{
"items": ["Nope", "I'm good"]
}
红色着色不适用于通过插槽添加的 a
标记元素。
我是 Svelte 的新手,但我通读了尽可能多的在线内容,但似乎找不到解决方案。任何帮助将不胜感激,谢谢。
这里的技巧是使用 :global(...)
修饰符选择加入级联。在您的列表组件中:
<style>
ul :global(a) {
color: red;
}
</style>
这意味着“作为该组件的 ul
元素的子元素的任何 a
元素,无论它们是否属于该组件,都应该是红色的”。
对于那些需要仅在插槽容器存在时才对其进行样式设置的用户
创建按钮组件
<button>
{#if $$slots['start-icon']}
<div class="m-4">
<slot name="start-icon" />
</div>
{/if}
<slot></slot>
</button>
用法
<button>
<Icon slot='start-icon' />
Button name
</button>
我希望将在一个模块中声明的样式应用到该模块的插槽元素(在另一个文件中填充)。
这是以下示例的 Svelte REPL:
App.html
<List>
{{#each items as item}}
<li><a>{{item}}</a></li>
{{/each}}
</List>
<script>
import List from './List.html'
export default {
components: {
List
}
}
</script>
List.html:
<h1>A Special List</h1>
<ul>
<li><a>Let's all be red!</a></li>
<slot></slot>
</ul>
<style>
ul a {
color: red;
}
</style>
数据:
{
"items": ["Nope", "I'm good"]
}
红色着色不适用于通过插槽添加的 a
标记元素。
我是 Svelte 的新手,但我通读了尽可能多的在线内容,但似乎找不到解决方案。任何帮助将不胜感激,谢谢。
这里的技巧是使用 :global(...)
修饰符选择加入级联。在您的列表组件中:
<style>
ul :global(a) {
color: red;
}
</style>
这意味着“作为该组件的 ul
元素的子元素的任何 a
元素,无论它们是否属于该组件,都应该是红色的”。
对于那些需要仅在插槽容器存在时才对其进行样式设置的用户
创建按钮组件
<button>
{#if $$slots['start-icon']}
<div class="m-4">
<slot name="start-icon" />
</div>
{/if}
<slot></slot>
</button>
用法
<button>
<Icon slot='start-icon' />
Button name
</button>