我正在嘗試設定一個帶有插槽的組件,該組件在呈現時會向該插槽的每個子項添加一個類。以一種非常簡化的方式:
<template>
<div>
<slot name="footerItems"></slot>
</div>
</template>
我該怎么辦?我當前的解決方案是將類添加到onBeforeUpdate鉤子中的元素:
<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>
但是,元素在重新渲染(使用npm run serve)時會丟失樣式,并且玩笑測驗會給我一個警告:
[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.
我應該將插槽移動到它自己的組件并在那里使用渲染函式嗎?但即便如此,我也不確定如何編輯子級以添加類或如何從渲染函式生成多個根級元素。
uj5u.com熱心網友回復:
你需要這個類來應用一些風格嗎?
您可以使用props傳遞樣式或類
并應用類或風格,:style=""或者:,它的解釋這里
但只為申請一門課,就:解決了你的問題
uj5u.com熱心網友回復:
所以,我設法以一種令人難以置信的駭人聽聞的方式解決了這個問題,但至少我的重新渲染問題不再發生,開玩笑也沒有抱怨。我寫了一個帶有渲染函式的組件,該函式將該類附加到所有子項
<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>
然后我只需將插槽包裝在此組件中以將類添加到子元素:
<template>
<div>
<classed-slot childrenClass="card-footer-item">
<slot name="footerItems"></slot>
</classed-slot>
</div>
</template>
我很樂意接受改進此解決方案的任何答案,尤其是:
- 任何鍵入它的提示。所有這些都
any感覺很奇怪,但我發現將 Vue 型別用于插槽是非常不切實際的,因為它們通常是 3 或 4 種型別的聯合,唯一的解決方案是將它們包裝在型別檢查中 - 任何提高其可靠性的東西,因為它似乎會在與我想要的設定略有不同的設定中崩潰
- 任何基于 Vue(或 TS)最佳實踐的建議,因為這看起來非常業余。
- 真的有任何其他方法來測驗符號相等性,因為我不知道
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398220.html
標籤:javascript Vue.js
