英文:
Working with slots and scoped css in Vuejs3
问题
I ran into the issue with Vue3 with slots and scoped css. Basically, I want to render some html based on component specific/scoped css.
Lets call the component Styler . This is how I would do that:
//Styler.vue
[...]
<template>
<article class="main">
<slot />
</article>
</template>
<style lang="css" scoped src="../css/styler.css"></style>
This result in all css selectors in styler.css to be propped with v-data-{rand-styler}
as expected, e.g. h1[v-data-{rand-styler}]
or .main h1[v-data-{rand-styler}]
if I nest it.
The problem is that when I use Styler
<Styler>
<h1>Style me Styler, style me away<h1>
</Styler>
the resulting html will not have h1 propped with v-data-{rand-styler}
only article will.
I would expect h1
to have scope attribute because in rendering in the context of Styler.
How one should work around it?
英文:
I ran into the issue with Vue3 with slots and scoped css. Basically, I want to render some html based on component specific/scoped css.
Lets call the component Styler . This is how I would do that:
//Styler.vue
[...]
<template>
<article class="main">
<slot />
</article>
</template>
<style lang="css" scoped src="../css/styler.css"></style>
This result in all css selectors in styler.css to be propped with v-data-{rand-styler}
as expected, e.g. h1[v-data-{rand-styler}]
or .main h1[v-data-{rand-styler}]
if I nest it.
The problem is that when I use Styler
<Styler>
<h1>Style me Styler, style me away<h1>
</Styler>
the resulting html will not have h1 propped with v-data-{rand-styler}
only article will.
I would expect h1
to have scope attribute, because in rendering in the context of Styler.
How one should work around it?
答案1
得分: 1
Slots是子组件,所以您需要使用:deep()
选择器来定位它们。
然后您会得到像[v-data-{rand-styler}] h1
这样的规则,它将影响子组件(确保插槽不是根元素,否则它将得到不同的属性)。
但看起来您的样式组件是专门设计用于应用样式于子元素的,所以可能更容易使用您自己的属性或类来确保只影响子元素:
<template>
<article class="main styler-styles">
<slot />
</article>
</template>
和
.styler-styles h1 {
...
}
英文:
Slots are child components, so you would have to use the :deep()
selector to target them.
Then you get rules like [v-data-{rand-styler}] h1
, which will affect child components (make sure the slot is not a root element, otherwise it will get a different attribute).
But it looks like your styler component is designed specifically to apply styles to children, so it is probably easier to use your own attribute or class to make sure only children are affected:
<template>
<article class="main styler-styles">
<slot />
</article>
</template>
and
.styler-styles h1{
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论