admin管理员组文章数量:1410731
I'm trying to set up a ponent with a slot, that when rendered adds a class to every children of that slot. In a very simplified manner:
<template>
<div>
<slot name="footerItems"></slot>
</div>
</template>
How would I go about this? My current solution is to add the class to the elements in an onBeforeUpdate
hook:
<script setup lang="ts">
import { useSlots, onMounted, onBeforeUpdate } from 'vue';
onBeforeUpdate(() => addClassToFooterItems());
onMounted(() => addClassToFooterItems());
function addClassToFooterItems() {
const slots = useSlots();
if (slots && slots.footerItems) {
for (const item of slots.footerItems()) {
item.el?.classList.add("card-footer-item");
}
}
}
</script>
However, the elements lose the styling whenever it's rerendered (using npm run serve
) and also jest tests give me a warning:
[Vue warn]: Slot "footerItems" invoked outside of the render function: this will not track dependencies used in the slot. Invoke the slot function inside the render function instead.
Should I move the slot to its own ponent and use a render function there? But even then I'm not sure how to edit the children to add the classes or how to produce several root level elements from the render function.
I'm trying to set up a ponent with a slot, that when rendered adds a class to every children of that slot. In a very simplified manner:
<template>
<div>
<slot name="footerItems"></slot>
</div>
</template>
How would I go about this? My current solution is to add the class to the elements in an onBeforeUpdate
hook:
<script setup lang="ts">
import { useSlots, onMounted, onBeforeUpdate } from 'vue';
onBeforeUpdate(() => addClassToFooterItems());
onMounted(() => addClassToFooterItems());
function addClassToFooterItems() {
const slots = useSlots();
if (slots && slots.footerItems) {
for (const item of slots.footerItems()) {
item.el?.classList.add("card-footer-item");
}
}
}
</script>
However, the elements lose the styling whenever it's rerendered (using npm run serve
) and also jest tests give me a warning:
[Vue warn]: Slot "footerItems" invoked outside of the render function: this will not track dependencies used in the slot. Invoke the slot function inside the render function instead.
Should I move the slot to its own ponent and use a render function there? But even then I'm not sure how to edit the children to add the classes or how to produce several root level elements from the render function.
Share edited Jan 17, 2022 at 11:25 Haf asked Dec 29, 2021 at 19:04 HafHaf 5772 gold badges6 silver badges18 bronze badges3 Answers
Reset to default 4So, I managed to solve this in an incredibly hacky way, but at least my issue with re-rendering doesn't happen anymore and jest doesn't plain. I wrote a ponent with a render function that appends that class to all children
<template>
<render>
<slot></slot>
</render>
</template>
<script setup lang="ts">
import { useSlots } from 'vue';
const props = defineProps<{
childrenClass: string;
}>();
function recurseIntoFragments(element: any): any {
if (element.type.toString() === 'Symbol(Fragment)'
&& element.children[0].type.toString() === 'Symbol(Fragment)'
) {
return recurseIntoFragments(element.children[0]);
} else {
return element;
}
}
const render = () => {
const slot = useSlots().default!();
recurseIntoFragments(slot[0]).children.forEach((element: any) => {
if (element.props?.class && !element.props?.class.includes(props.childrenClass)) {
element.props.class += ` ${props.childrenClass}`;
} else {
element.props.class = props.childrenClass;
}
});
return slot;
}
</script>
Then I would just wrap the slot in this ponent to add the class to the children elements:
<template>
<div>
<classed-slot childrenClass="card-footer-item">
<slot name="footerItems"></slot>
</classed-slot>
</div>
</template>
I would gladly accept any answer that improves upon this solution, especially:
- Any tips to type it. All those
any
s feel wonky but I find it very impractical working with Vue types for slots since they are usually unions of 3 or 4 types and the only solution is to wrap these in type checks - Anything that improves its reliability since it seems that it'd crash in any slightly different setup than the one I intended
- Any remendation based on Vue's (or TS) best practices, since this looks very amateurish.
- Really any other way to test for symbol equality because I know none
EDIT
This is my latest attempt, a render function in a file ClassedSlot.js
:
import { cloneVNode } from 'vue';
function recursivelyAddClass(element, classToAdd) {
if (Array.isArray(element)) {
return element.map(el => recursivelyAddClass(el, classToAdd));
} else if (element.type.toString() === 'Symbol(Fragment)') {
const clone = cloneVNode(element);
clone.children = recursivelyAddClass(element.children, classToAdd)
return clone;
} else {
return cloneVNode(element, { class: classToAdd });
}
}
export default {
props: {
childrenClass: {
type: String,
required: true
},
},
render() {
const slot = this.$slots.default();
return recursivelyAddClass(slot, this.$props.childrenClass);
},
};
The usage of this ponent is exactly the same as in the previous one. I'm kinda happy with this solution, seems more robust and idiomatic. Note that it's javascript because I found it really hard to type these functions correctly.
@Haf 's answer is good.
I made some adjustments, so that you can specify the ponent name.
import { FunctionalComponent, StyleValue, cloneVNode, Ref, ComputedRef, unref } from "vue";
type MaybeRef<T> = T | Ref<T>;
/**
* @param extraProps - ref or normal object
* @returns
*
* @example
*
* const StyleComponent = useCssInJs({class: 'text-red-500'});
*
* const ComponentA = () => {
* return <StyleComponent><span>text is red-500</span></StyleComponent>
* }
*/
export const useCssInJs = (extraProps: MaybeRef<{
class?: string,
style?: StyleValue
}>) => {
const FnComponent: FunctionalComponent = (_, { slots }) => {
const defaultSlot = slots.default?.()[0];
// could be Fragment or others? I'm just ignoring these case here
if (!defaultSlot) return;
const node = cloneVNode(defaultSlot, unref(extraProps));
return [node];
};
return FnComponent
}
My solution with TS
<template>
<render>
<slot></slot>
</render>
</template>
<script setup lang='ts'>
import { cloneVNode, useAttrs, useSlots, type VNode } from 'vue'
const att = useAttrs()
function recursivelyAddProps(element: VNode): VNode | Array<VNode> {
if (Array.isArray(element?.children)) {
return element.children.map((el) => recursivelyAddProps(el as VNode)) as Array<VNode>
} else {
return cloneVNode(element, att)
}
}
const render = () => {
const slot = useSlots()?.default!()
return recursivelyAddProps(slot[0])
}
</script>
And usage
<ExtendedSlot class='dropdown-item'>
<slot></slot>
</ExtendedSlot>
本文标签: javascriptAdd a class to every child of a slotStack Overflow
版权声明:本文标题:javascript - Add a class to every child of a slot - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744924799a2632527.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论